This is the multi-page printable view of this section. Click here to print.
Leetcode submissions
Leetcode submissions
- 1: 2025-09-22 19:34:44 +0300 MSK
- 2: 2025-09-21 19:30:58 +0300 MSK
- 3: 2025-09-20 19:25:16 +0300 MSK
- 4: 2025-09-19 18:44:46 +0300 MSK
- 5: 2025-09-18 19:58:25 +0300 MSK
- 6: 2025-09-17 20:39:54 +0300 MSK
- 7: 2025-09-16 18:41:40 +0300 MSK
- 8: 2025-09-15 18:04:52 +0300 MSK
- 9: 2025-09-14 19:11:43 +0300 MSK
- 10: 2025-09-13 18:48:49 +0300 MSK
- 11: 2025-09-12 21:22:49 +0300 MSK
- 12: 2025-09-11 20:29:02 +0300 MSK
- 13: 2025-09-10 18:11:04 +0300 MSK
- 14: 2025-09-09 18:44:51 +0300 MSK
- 15: 2025-09-08 18:09:53 +0300 MSK
- 16: 2025-09-07 11:16:52 +0300 MSK
- 17: 2025-09-07 11:00:41 +0300 MSK
- 18: 2025-09-06 17:38:19 +0300 MSK
- 19: 2025-09-05 19:23:51 +0300 MSK
- 20: 2025-09-04 22:15:30 +0300 MSK
- 21: 2025-09-03 18:20:51 +0300 MSK
- 22: 2025-09-02 20:18:23 +0300 MSK
- 23: 2025-09-01 17:35:05 +0300 MSK
- 24: 2025-08-31 15:07:32 +0300 MSK
- 25: 2025-08-31 14:18:46 +0300 MSK
- 26: 2025-08-31 14:13:40 +0300 MSK
- 27: 2025-08-30 20:16:00 +0300 MSK
- 28: 2025-08-29 19:59:52 +0300 MSK
- 29: 2025-08-28 16:59:23 +0300 MSK
- 30: 2025-08-27 16:22:50 +0300 MSK
- 31: 2025-08-26 09:10:25 +0300 MSK
- 32: 2025-08-26 08:16:39 +0300 MSK
- 33: 2025-08-26 08:11:15 +0300 MSK
- 34: 2025-08-25 17:00:38 +0300 MSK
- 35: 2025-08-25 11:40:44 +0300 MSK
- 36: 2025-08-24 20:51:14 +0300 MSK
- 37: 2025-08-24 19:54:22 +0300 MSK
- 38: 2025-08-24 19:38:13 +0300 MSK
- 39: 2025-08-24 19:30:45 +0300 MSK
- 40: 2025-08-24 19:28:22 +0300 MSK
- 41: 2025-08-24 19:26:17 +0300 MSK
- 42: 2025-08-24 19:18:26 +0300 MSK
- 43: 2025-08-24 19:07:06 +0300 MSK
- 44: 2025-08-24 19:02:12 +0300 MSK
- 45: 2025-08-24 18:57:13 +0300 MSK
- 46: 2025-08-24 18:52:47 +0300 MSK
- 47: 2025-08-24 18:50:32 +0300 MSK
- 48: 2025-08-24 18:39:15 +0300 MSK
- 49: 2025-08-24 18:38:15 +0300 MSK
- 50: 2025-08-24 18:22:04 +0300 MSK
- 51: 2025-08-24 18:15:48 +0300 MSK
- 52: 2025-08-24 18:07:04 +0300 MSK
- 53: 2025-08-24 18:01:04 +0300 MSK
- 54: 2025-08-24 17:55:59 +0300 MSK
- 55: 2025-08-24 17:54:29 +0300 MSK
- 56: 2025-08-24 17:52:40 +0300 MSK
- 57: 2025-08-24 17:46:18 +0300 MSK
- 58: 2025-08-24 17:42:32 +0300 MSK
- 59: 2025-08-24 17:41:29 +0300 MSK
- 60: 2025-08-24 17:40:23 +0300 MSK
- 61: 2025-08-24 17:38:35 +0300 MSK
- 62: 2025-08-24 17:36:34 +0300 MSK
- 63: 2025-08-24 17:22:24 +0300 MSK
- 64: 2025-08-24 17:12:42 +0300 MSK
- 65: 2025-08-24 17:10:49 +0300 MSK
- 66: 2025-08-24 17:08:09 +0300 MSK
- 67: 2025-08-24 17:02:11 +0300 MSK
- 68: 2025-08-24 16:02:46 +0300 MSK
- 69: 2025-08-24 16:00:53 +0300 MSK
- 70: 2025-08-24 15:55:14 +0300 MSK
- 71: 2025-08-24 15:40:47 +0300 MSK
- 72: 2025-08-24 15:35:22 +0300 MSK
- 73: 2025-08-24 15:32:58 +0300 MSK
- 74: 2025-08-24 15:21:21 +0300 MSK
- 75: 2025-08-24 15:17:24 +0300 MSK
- 76: 2025-08-24 15:14:50 +0300 MSK
- 77: 2025-08-24 15:11:09 +0300 MSK
- 78: 2025-08-24 15:07:53 +0300 MSK
- 79: 2025-08-24 15:06:30 +0300 MSK
- 80: 2025-08-24 15:00:31 +0300 MSK
- 81: 2025-08-24 14:57:30 +0300 MSK
- 82: 2025-08-24 14:47:52 +0300 MSK
- 83: 2025-08-24 14:42:38 +0300 MSK
- 84: 2025-08-24 14:38:49 +0300 MSK
- 85: 2025-08-24 14:36:54 +0300 MSK
- 86: 2025-08-24 14:33:39 +0300 MSK
- 87: 2025-08-24 14:28:25 +0300 MSK
- 88: 2025-08-24 14:25:47 +0300 MSK
- 89: 2025-08-24 14:09:37 +0300 MSK
- 90: 2025-08-24 14:03:51 +0300 MSK
- 91: 2025-08-24 13:57:16 +0300 MSK
- 92: 2025-08-24 13:46:58 +0300 MSK
- 93: 2025-08-24 13:33:19 +0300 MSK
- 94: 2025-08-24 13:31:22 +0300 MSK
- 95: 2025-08-24 13:27:05 +0300 MSK
- 96: 2025-08-24 13:21:47 +0300 MSK
- 97: 2025-08-24 13:10:51 +0300 MSK
- 98: 2025-08-24 13:05:10 +0300 MSK
- 99: 2025-08-24 12:59:57 +0300 MSK
- 100: 2025-08-24 12:47:23 +0300 MSK
- 101: 2025-08-24 12:44:46 +0300 MSK
- 102: 2025-08-24 12:44:03 +0300 MSK
- 103: 2025-08-24 12:38:10 +0300 MSK
- 104: 2025-08-24 12:34:32 +0300 MSK
- 105: 2025-08-24 12:31:27 +0300 MSK
- 106: 2025-08-24 12:29:48 +0300 MSK
- 107: 2025-08-24 12:20:45 +0300 MSK
- 108: 2025-08-24 11:46:23 +0300 MSK
- 109: 2025-08-24 11:43:54 +0300 MSK
- 110: 2025-08-24 10:55:08 +0300 MSK
- 111: 2025-08-23 20:17:19 +0300 MSK
- 112: 2025-08-23 19:28:34 +0300 MSK
- 113: 2025-08-23 18:30:08 +0300 MSK
- 114: 2025-08-22 21:36:17 +0300 MSK
- 115: 2025-08-22 21:29:25 +0300 MSK
- 116: 2025-08-22 21:16:52 +0300 MSK
- 117: 2025-08-22 21:13:56 +0300 MSK
- 118: 2025-08-22 21:08:45 +0300 MSK
- 119: 2025-08-22 21:06:36 +0300 MSK
- 120: 2025-08-22 21:05:07 +0300 MSK
- 121: 2025-08-22 21:02:15 +0300 MSK
- 122: 2025-08-22 20:53:33 +0300 MSK
- 123: 2025-08-22 20:44:21 +0300 MSK
- 124: 2025-08-22 20:41:37 +0300 MSK
- 125: 2025-08-22 20:34:34 +0300 MSK
- 126: 2025-08-22 20:29:48 +0300 MSK
- 127: 2025-08-22 20:27:37 +0300 MSK
- 128: 2025-08-22 20:25:28 +0300 MSK
- 129: 2025-08-22 20:22:48 +0300 MSK
- 130: 2025-08-22 20:20:58 +0300 MSK
- 131: 2025-08-22 20:15:56 +0300 MSK
- 132: 2025-08-22 20:12:59 +0300 MSK
- 133: 2025-08-22 20:03:50 +0300 MSK
- 134: 2025-08-22 19:58:17 +0300 MSK
- 135: 2025-08-22 19:49:07 +0300 MSK
- 136: 2025-08-22 19:43:35 +0300 MSK
- 137: 2025-08-22 19:42:24 +0300 MSK
- 138: 2025-08-22 19:24:16 +0300 MSK
- 139: 2025-08-22 19:19:46 +0300 MSK
- 140: 2025-08-22 19:14:44 +0300 MSK
- 141: 2025-08-22 19:10:19 +0300 MSK
- 142: 2025-08-22 19:03:00 +0300 MSK
- 143: 2025-08-22 18:58:03 +0300 MSK
- 144: 2025-08-22 18:56:27 +0300 MSK
- 145: 2025-08-22 18:53:34 +0300 MSK
- 146: 2025-08-22 18:48:54 +0300 MSK
- 147: 2025-08-22 18:46:45 +0300 MSK
- 148: 2025-08-22 18:44:22 +0300 MSK
- 149: 2025-08-22 18:43:10 +0300 MSK
- 150: 2025-08-22 18:39:40 +0300 MSK
- 151: 2025-08-22 18:38:14 +0300 MSK
- 152: 2025-08-22 18:36:52 +0300 MSK
- 153: 2025-08-22 18:30:44 +0300 MSK
- 154: 2025-08-22 18:25:20 +0300 MSK
- 155: 2025-08-22 18:22:55 +0300 MSK
- 156: 2025-08-22 18:19:44 +0300 MSK
- 157: 2025-08-22 17:02:28 +0300 MSK
- 158: 2025-08-22 16:56:33 +0300 MSK
- 159: 2025-08-22 14:49:18 +0300 MSK
- 160: 2025-08-22 14:41:39 +0300 MSK
- 161: 2025-08-22 14:33:33 +0300 MSK
- 162: 2025-08-22 14:30:04 +0300 MSK
- 163: 2025-08-22 14:28:05 +0300 MSK
- 164: 2025-08-22 14:23:13 +0300 MSK
- 165: 2025-08-22 14:20:44 +0300 MSK
- 166: 2025-08-22 14:19:56 +0300 MSK
- 167: 2025-08-22 14:06:34 +0300 MSK
- 168: 2025-08-22 13:59:13 +0300 MSK
- 169: 2025-08-22 13:58:21 +0300 MSK
- 170: 2025-08-22 13:53:08 +0300 MSK
- 171: 2025-08-22 13:44:20 +0300 MSK
- 172: 2025-08-22 13:37:11 +0300 MSK
- 173: 2025-08-22 09:54:03 +0300 MSK
- 174: 2025-08-21 19:04:22 +0300 MSK
- 175: 2025-08-21 19:01:40 +0300 MSK
- 176: 2025-08-21 18:59:14 +0300 MSK
- 177: 2025-08-21 18:58:06 +0300 MSK
- 178: 2025-08-21 18:57:41 +0300 MSK
- 179: 2025-08-21 18:50:35 +0300 MSK
- 180: 2025-08-21 18:50:21 +0300 MSK
- 181: 2025-08-21 18:45:02 +0300 MSK
- 182: 2025-08-21 18:35:19 +0300 MSK
- 183: 2025-08-21 18:35:00 +0300 MSK
- 184: 2025-08-21 18:34:31 +0300 MSK
- 185: 2025-08-21 18:30:25 +0300 MSK
- 186: 2025-08-21 18:30:11 +0300 MSK
- 187: 2025-08-21 18:24:42 +0300 MSK
- 188: 2025-08-21 18:24:23 +0300 MSK
- 189: 2025-08-21 18:18:09 +0300 MSK
- 190: 2025-08-21 18:17:44 +0300 MSK
- 191: 2025-08-21 18:17:05 +0300 MSK
- 192: 2025-08-21 18:16:46 +0300 MSK
- 193: 2025-08-21 18:16:25 +0300 MSK
- 194: 2025-08-21 18:16:06 +0300 MSK
- 195: 2025-08-21 18:15:24 +0300 MSK
- 196: 2025-08-21 17:56:20 +0300 MSK
- 197: 2025-08-21 17:51:03 +0300 MSK
- 198: 2025-08-21 17:41:49 +0300 MSK
- 199: 2025-08-21 17:35:46 +0300 MSK
- 200: 2025-08-21 17:31:03 +0300 MSK
- 201: 2025-08-21 17:26:29 +0300 MSK
- 202: 2025-08-21 17:15:57 +0300 MSK
- 203: 2025-08-21 17:07:52 +0300 MSK
- 204: 2025-08-21 17:05:33 +0300 MSK
- 205: 2025-08-21 17:00:40 +0300 MSK
- 206: 2025-08-21 16:51:13 +0300 MSK
- 207: 2025-08-21 16:50:01 +0300 MSK
- 208: 2025-08-21 16:46:44 +0300 MSK
- 209: 2025-08-21 16:44:37 +0300 MSK
- 210: 2025-08-21 16:42:44 +0300 MSK
- 211: 2025-08-21 16:38:20 +0300 MSK
- 212: 2025-08-21 16:26:55 +0300 MSK
- 213: 2025-08-21 16:19:42 +0300 MSK
- 214: 2025-08-21 16:16:56 +0300 MSK
- 215: 2025-08-21 16:07:01 +0300 MSK
- 216: 2025-08-21 16:06:09 +0300 MSK
- 217: 2025-08-21 16:01:02 +0300 MSK
- 218: 2025-08-21 15:58:36 +0300 MSK
- 219: 2025-08-21 15:55:14 +0300 MSK
- 220: 2025-08-21 15:49:02 +0300 MSK
- 221: 2025-08-21 15:45:35 +0300 MSK
- 222: 2025-08-21 15:42:45 +0300 MSK
- 223: 2025-08-21 15:40:49 +0300 MSK
- 224: 2025-08-21 15:37:36 +0300 MSK
- 225: 2025-08-21 15:33:15 +0300 MSK
- 226: 2025-08-21 15:32:49 +0300 MSK
- 227: 2025-08-21 15:03:03 +0300 MSK
- 228: 2025-08-21 14:57:54 +0300 MSK
- 229: 2025-08-21 14:56:18 +0300 MSK
- 230: 2025-08-21 14:52:44 +0300 MSK
- 231: 2025-08-21 14:47:10 +0300 MSK
- 232: 2025-08-21 14:44:56 +0300 MSK
- 233: 2025-08-21 14:42:42 +0300 MSK
- 234: 2025-08-21 14:32:28 +0300 MSK
- 235: 2025-08-21 14:31:55 +0300 MSK
- 236: 2025-08-21 14:30:46 +0300 MSK
- 237: 2025-08-21 14:28:11 +0300 MSK
- 238: 2025-08-21 14:14:45 +0300 MSK
- 239: 2025-08-21 14:03:34 +0300 MSK
- 240: 2025-08-21 13:59:45 +0300 MSK
- 241: 2025-08-21 13:58:37 +0300 MSK
- 242: 2025-08-21 13:56:09 +0300 MSK
- 243: 2025-08-21 13:42:53 +0300 MSK
- 244: 2025-08-21 13:40:48 +0300 MSK
- 245: 2025-08-21 13:31:24 +0300 MSK
- 246: 2025-08-21 13:26:07 +0300 MSK
- 247: 2025-08-21 12:41:54 +0300 MSK
- 248: 2025-08-21 12:07:22 +0300 MSK
- 249: 2025-08-21 11:45:30 +0300 MSK
- 250: 2025-08-21 11:32:12 +0300 MSK
- 251: 2025-08-21 11:29:38 +0300 MSK
- 252: 2025-08-21 11:16:33 +0300 MSK
- 253: 2025-08-21 11:08:30 +0300 MSK
- 254: 2025-08-21 08:52:21 +0300 MSK
- 255: 2025-08-20 20:41:08 +0300 MSK
- 256: 2025-08-20 20:38:27 +0300 MSK
- 257: 2025-08-20 20:36:18 +0300 MSK
- 258: 2025-08-20 20:31:33 +0300 MSK
- 259: 2025-08-20 20:28:21 +0300 MSK
- 260: 2025-08-20 20:26:57 +0300 MSK
- 261: 2025-08-20 20:25:45 +0300 MSK
- 262: 2025-08-20 20:20:02 +0300 MSK
- 263: 2025-08-20 20:15:03 +0300 MSK
- 264: 2025-08-20 20:10:18 +0300 MSK
- 265: 2025-08-20 19:48:54 +0300 MSK
- 266: 2025-08-20 19:41:49 +0300 MSK
- 267: 2025-08-20 19:24:46 +0300 MSK
- 268: 2025-08-20 19:22:34 +0300 MSK
- 269: 2025-08-20 19:11:13 +0300 MSK
- 270: 2025-08-20 19:07:59 +0300 MSK
- 271: 2025-08-20 19:05:44 +0300 MSK
- 272: 2025-08-20 19:01:55 +0300 MSK
- 273: 2025-08-20 18:54:48 +0300 MSK
- 274: 2025-08-20 18:49:12 +0300 MSK
- 275: 2025-08-20 18:45:47 +0300 MSK
- 276: 2025-08-20 18:44:00 +0300 MSK
- 277: 2025-08-20 18:28:35 +0300 MSK
- 278: 2025-08-20 18:24:20 +0300 MSK
- 279: 2025-08-20 18:23:07 +0300 MSK
- 280: 2025-08-20 18:22:39 +0300 MSK
- 281: 2025-08-20 17:57:07 +0300 MSK
- 282: 2025-08-20 17:48:38 +0300 MSK
- 283: 2025-08-20 17:47:52 +0300 MSK
- 284: 2025-08-20 17:43:24 +0300 MSK
- 285: 2025-08-20 17:23:29 +0300 MSK
- 286: 2025-08-20 17:18:47 +0300 MSK
- 287: 2025-08-20 15:09:02 +0300 MSK
- 288: 2025-08-20 13:48:16 +0300 MSK
- 289: 2025-08-20 13:45:38 +0300 MSK
- 290: 2025-08-20 13:41:05 +0300 MSK
- 291: 2025-08-20 13:36:58 +0300 MSK
- 292: 2025-08-20 13:29:30 +0300 MSK
- 293: 2025-08-20 13:16:55 +0300 MSK
- 294: 2025-08-20 13:13:48 +0300 MSK
- 295: 2025-08-20 13:06:17 +0300 MSK
- 296: 2025-08-20 12:43:09 +0300 MSK
- 297: 2025-08-20 12:38:03 +0300 MSK
- 298: 2025-08-20 12:08:13 +0300 MSK
- 299: 2025-08-19 20:23:46 +0300 MSK
- 300: 2025-08-19 20:13:25 +0300 MSK
- 301: 2025-08-19 20:11:33 +0300 MSK
- 302: 2025-08-19 20:00:15 +0300 MSK
- 303: 2025-08-19 19:47:47 +0300 MSK
- 304: 2025-08-19 16:10:29 +0300 MSK
- 305: 2025-08-19 15:27:24 +0300 MSK
- 306: 2025-08-19 15:24:40 +0300 MSK
- 307: 2025-08-19 15:04:21 +0300 MSK
- 308: 2025-08-19 14:58:59 +0300 MSK
- 309: 2025-08-19 14:42:34 +0300 MSK
- 310: 2025-08-19 14:37:35 +0300 MSK
- 311: 2025-08-19 14:29:00 +0300 MSK
- 312: 2025-08-19 14:04:31 +0300 MSK
- 313: 2025-08-19 13:54:21 +0300 MSK
- 314: 2025-08-19 13:40:19 +0300 MSK
- 315: 2025-08-19 13:37:47 +0300 MSK
- 316: 2025-08-19 13:11:40 +0300 MSK
- 317: 2025-08-19 11:34:12 +0300 MSK
- 318: 2025-08-19 09:58:54 +0300 MSK
- 319: 2025-08-19 08:52:54 +0300 MSK
- 320: 2025-08-19 08:18:09 +0300 MSK
- 321: 2025-08-18 21:10:17 +0300 MSK
- 322: 2025-08-18 21:06:45 +0300 MSK
- 323: 2025-08-18 20:23:18 +0300 MSK
- 324: 2025-08-18 20:18:16 +0300 MSK
- 325: 2025-08-18 20:07:07 +0300 MSK
- 326: 2025-08-18 20:04:04 +0300 MSK
- 327: 2025-08-18 19:52:53 +0300 MSK
- 328: 2025-08-18 19:41:27 +0300 MSK
- 329: 2025-08-18 19:36:10 +0300 MSK
- 330: 2025-08-18 19:26:10 +0300 MSK
- 331: 2025-08-18 19:21:41 +0300 MSK
- 332: 2025-08-18 19:16:20 +0300 MSK
- 333: 2025-08-18 19:11:33 +0300 MSK
- 334: 2025-08-18 19:02:01 +0300 MSK
- 335: 2025-08-18 18:43:22 +0300 MSK
- 336: 2025-08-18 15:12:00 +0300 MSK
- 337: 2025-08-18 15:03:06 +0300 MSK
- 338: 2025-08-18 14:55:52 +0300 MSK
- 339: 2025-08-18 14:48:14 +0300 MSK
- 340: 2025-08-18 14:43:36 +0300 MSK
- 341: 2025-08-18 13:44:46 +0300 MSK
- 342: 2025-08-18 13:40:40 +0300 MSK
- 343: 2025-08-18 13:34:09 +0300 MSK
- 344: 2025-08-18 10:06:49 +0300 MSK
- 345: 2025-08-17 20:02:56 +0300 MSK
- 346: 2025-08-17 19:56:52 +0300 MSK
- 347: 2025-08-17 19:54:48 +0300 MSK
- 348: 2025-08-17 19:44:55 +0300 MSK
- 349: 2025-08-17 19:21:20 +0300 MSK
- 350: 2025-08-17 19:15:00 +0300 MSK
- 351: 2025-08-17 19:10:32 +0300 MSK
- 352: 2025-08-17 19:08:02 +0300 MSK
- 353: 2025-08-17 18:51:40 +0300 MSK
- 354: 2025-08-17 18:46:10 +0300 MSK
- 355: 2025-08-17 18:44:14 +0300 MSK
- 356: 2025-08-17 18:40:15 +0300 MSK
- 357: 2025-08-17 18:38:02 +0300 MSK
- 358: 2025-08-17 18:25:12 +0300 MSK
- 359: 2025-08-17 18:16:02 +0300 MSK
- 360: 2025-08-17 18:06:00 +0300 MSK
- 361: 2025-08-17 17:56:42 +0300 MSK
- 362: 2025-08-17 17:28:49 +0300 MSK
- 363: 2025-08-17 17:16:59 +0300 MSK
- 364: 2025-08-17 17:04:01 +0300 MSK
- 365: 2025-08-17 16:00:07 +0300 MSK
- 366: 2025-08-17 13:53:56 +0300 MSK
- 367: 2025-08-17 13:41:15 +0300 MSK
- 368: 2025-08-17 13:38:02 +0300 MSK
- 369: 2025-08-17 13:36:24 +0300 MSK
- 370: 2025-08-17 13:34:11 +0300 MSK
- 371: 2025-08-17 13:25:54 +0300 MSK
- 372: 2025-08-17 13:10:43 +0300 MSK
- 373: 2025-08-17 12:55:05 +0300 MSK
- 374: 2025-08-17 12:47:03 +0300 MSK
- 375: 2025-08-17 12:39:05 +0300 MSK
- 376: 2025-08-17 11:54:12 +0300 MSK
- 377: 2025-08-17 09:23:21 +0300 MSK
- 378: 2025-08-16 18:43:20 +0300 MSK
- 379: 2025-08-16 16:51:28 +0300 MSK
- 380: 2025-08-16 16:11:23 +0300 MSK
- 381: 2025-08-16 14:42:51 +0300 MSK
- 382: 2025-08-16 14:31:57 +0300 MSK
- 383: 2025-08-16 14:30:59 +0300 MSK
- 384: 2025-08-16 14:27:06 +0300 MSK
- 385: 2025-08-16 14:19:48 +0300 MSK
- 386: 2025-08-16 14:16:53 +0300 MSK
- 387: 2025-08-16 14:14:34 +0300 MSK
- 388: 2025-08-16 14:05:37 +0300 MSK
- 389: 2025-08-16 14:04:12 +0300 MSK
- 390: 2025-08-16 13:53:07 +0300 MSK
- 391: 2025-08-16 13:39:08 +0300 MSK
- 392: 2025-08-16 13:35:39 +0300 MSK
- 393: 2025-08-16 13:22:50 +0300 MSK
- 394: 2025-08-16 13:15:31 +0300 MSK
- 395: 2025-08-16 13:13:30 +0300 MSK
- 396: 2025-08-16 12:59:52 +0300 MSK
- 397: 2025-08-16 12:54:52 +0300 MSK
- 398: 2025-08-16 12:42:27 +0300 MSK
- 399: 2025-08-16 12:24:35 +0300 MSK
- 400: 2025-08-16 12:19:08 +0300 MSK
- 401: 2025-08-16 12:12:54 +0300 MSK
- 402: 2025-08-16 12:11:17 +0300 MSK
- 403: 2025-08-16 12:07:23 +0300 MSK
- 404: 2025-08-16 12:06:11 +0300 MSK
- 405: 2025-08-16 11:58:38 +0300 MSK
- 406: 2025-08-16 11:50:13 +0300 MSK
- 407: 2025-08-16 11:32:58 +0300 MSK
- 408: 2025-08-16 11:14:35 +0300 MSK
- 409: 2025-08-16 11:13:51 +0300 MSK
- 410: 2025-08-16 11:09:17 +0300 MSK
- 411: 2025-08-16 10:49:39 +0300 MSK
- 412: 2025-08-16 10:22:08 +0300 MSK
- 413: 2025-08-16 10:19:18 +0300 MSK
- 414: 2025-08-16 10:09:43 +0300 MSK
- 415: 2025-08-15 17:31:44 +0300 MSK
- 416: 2025-08-15 16:57:42 +0300 MSK
- 417: 2025-08-15 16:43:07 +0300 MSK
- 418: 2025-08-15 16:35:39 +0300 MSK
- 419: 2025-08-15 16:30:08 +0300 MSK
- 420: 2025-08-15 16:25:44 +0300 MSK
- 421: 2025-08-15 16:20:07 +0300 MSK
- 422: 2025-08-15 16:13:25 +0300 MSK
- 423: 2025-08-15 16:11:57 +0300 MSK
- 424: 2025-08-15 16:11:03 +0300 MSK
- 425: 2025-08-15 16:06:24 +0300 MSK
- 426: 2025-08-15 16:05:32 +0300 MSK
- 427: 2025-08-15 16:03:03 +0300 MSK
- 428: 2025-08-15 15:54:30 +0300 MSK
- 429: 2025-08-15 15:47:22 +0300 MSK
- 430: 2025-08-15 15:44:11 +0300 MSK
- 431: 2025-08-15 15:38:40 +0300 MSK
- 432: 2025-08-15 15:32:17 +0300 MSK
- 433: 2025-08-15 15:28:53 +0300 MSK
- 434: 2025-08-15 15:12:21 +0300 MSK
- 435: 2025-08-15 15:04:18 +0300 MSK
- 436: 2025-08-15 15:03:12 +0300 MSK
- 437: 2025-08-15 14:37:22 +0300 MSK
- 438: 2025-08-15 14:34:58 +0300 MSK
- 439: 2025-08-15 14:33:22 +0300 MSK
- 440: 2025-08-15 14:31:10 +0300 MSK
- 441: 2025-08-15 14:21:42 +0300 MSK
- 442: 2025-08-15 14:17:27 +0300 MSK
- 443: 2025-08-15 14:14:49 +0300 MSK
- 444: 2025-08-15 13:38:16 +0300 MSK
- 445: 2025-08-15 13:31:41 +0300 MSK
- 446: 2025-08-15 13:23:40 +0300 MSK
- 447: 2025-08-15 13:09:22 +0300 MSK
- 448: 2025-08-15 13:07:52 +0300 MSK
- 449: 2025-08-15 12:54:27 +0300 MSK
- 450: 2025-08-15 12:49:02 +0300 MSK
- 451: 2025-08-15 12:36:30 +0300 MSK
- 452: 2025-08-15 12:28:46 +0300 MSK
- 453: 2025-08-15 12:22:34 +0300 MSK
- 454: 2025-08-15 11:52:01 +0300 MSK
- 455: 2025-08-15 11:51:01 +0300 MSK
- 456: 2025-08-14 20:09:09 +0300 MSK
- 457: 2025-08-13 17:56:30 +0300 MSK
- 458: 2025-08-13 17:55:25 +0300 MSK
- 459: 2025-08-12 17:49:12 +0300 MSK
- 460: 2025-08-11 18:03:04 +0300 MSK
- 461: 2025-08-10 13:14:07 +0300 MSK
- 462: 2025-08-10 13:10:37 +0300 MSK
- 463: 2025-08-10 13:08:24 +0300 MSK
- 464: 2025-08-10 13:03:22 +0300 MSK
- 465: 2025-08-10 12:56:18 +0300 MSK
- 466: 2025-08-10 12:52:07 +0300 MSK
- 467: 2025-08-10 12:45:06 +0300 MSK
- 468: 2025-08-10 12:15:52 +0300 MSK
- 469: 2025-08-10 11:45:24 +0300 MSK
- 470: 2025-08-10 11:25:09 +0300 MSK
- 471: 2025-08-10 11:14:30 +0300 MSK
- 472: 2025-08-10 11:02:20 +0300 MSK
- 473: 2025-08-10 10:27:29 +0300 MSK
- 474: 2025-08-09 16:43:21 +0300 MSK
- 475: 2025-08-09 16:34:28 +0300 MSK
- 476: 2025-08-09 16:31:49 +0300 MSK
- 477: 2025-08-09 16:17:16 +0300 MSK
- 478: 2025-08-09 15:53:09 +0300 MSK
- 479: 2025-08-09 11:14:40 +0300 MSK
- 480: 2025-08-08 18:19:33 +0300 MSK
- 481: 2025-08-07 17:57:34 +0300 MSK
- 482: 2025-08-07 17:15:08 +0300 MSK
- 483: 2025-08-06 19:26:47 +0300 MSK
- 484: 2025-08-06 16:17:09 +0300 MSK
- 485: 2025-08-05 20:11:10 +0300 MSK
- 486: 2025-08-04 19:06:02 +0300 MSK
- 487: 2025-08-03 16:36:16 +0300 MSK
- 488: 2025-08-03 16:21:01 +0300 MSK
- 489: 2025-08-03 16:03:54 +0300 MSK
- 490: 2025-08-03 15:13:16 +0300 MSK
- 491: 2025-08-03 15:01:18 +0300 MSK
- 492: 2025-08-03 14:57:57 +0300 MSK
- 493: 2025-08-03 14:56:16 +0300 MSK
- 494: 2025-08-03 14:39:49 +0300 MSK
- 495: 2025-08-03 14:36:46 +0300 MSK
- 496: 2025-08-03 14:33:50 +0300 MSK
- 497: 2025-08-03 14:29:35 +0300 MSK
- 498: 2025-08-03 14:27:36 +0300 MSK
- 499: 2025-08-03 14:18:22 +0300 MSK
- 500: 2025-08-03 14:14:27 +0300 MSK
- 501: 2025-08-03 13:56:55 +0300 MSK
- 502: 2025-08-03 13:42:44 +0300 MSK
- 503: 2025-08-03 13:35:23 +0300 MSK
- 504: 2025-08-03 13:30:55 +0300 MSK
- 505: 2025-08-03 13:25:11 +0300 MSK
- 506: 2025-08-03 13:22:53 +0300 MSK
- 507: 2025-08-03 13:19:10 +0300 MSK
- 508: 2025-08-03 11:38:37 +0300 MSK
- 509: 2025-08-03 10:42:15 +0300 MSK
- 510: 2025-08-03 10:26:28 +0300 MSK
- 511: 2025-08-02 20:09:46 +0300 MSK
- 512: 2025-08-02 20:03:30 +0300 MSK
- 513: 2025-08-02 19:58:48 +0300 MSK
- 514: 2025-08-02 19:54:21 +0300 MSK
- 515: 2025-08-02 19:50:44 +0300 MSK
- 516: 2025-08-02 19:45:12 +0300 MSK
- 517: 2025-08-02 19:36:06 +0300 MSK
- 518: 2025-08-02 19:28:39 +0300 MSK
- 519: 2025-08-02 19:24:42 +0300 MSK
- 520: 2025-08-02 19:22:20 +0300 MSK
- 521: 2025-08-02 19:12:42 +0300 MSK
- 522: 2025-08-02 19:08:24 +0300 MSK
- 523: 2025-08-02 18:59:52 +0300 MSK
- 524: 2025-08-02 18:49:48 +0300 MSK
- 525: 2025-08-02 18:45:57 +0300 MSK
- 526: 2025-08-02 18:40:13 +0300 MSK
- 527: 2025-08-02 18:33:48 +0300 MSK
- 528: 2025-08-02 18:22:51 +0300 MSK
- 529: 2025-08-02 18:14:37 +0300 MSK
- 530: 2025-08-02 18:07:54 +0300 MSK
- 531: 2025-08-02 18:04:04 +0300 MSK
- 532: 2025-08-02 17:59:03 +0300 MSK
- 533: 2025-08-02 17:54:14 +0300 MSK
- 534: 2025-08-02 17:28:54 +0300 MSK
- 535: 2025-08-02 17:26:28 +0300 MSK
- 536: 2025-08-02 17:24:46 +0300 MSK
- 537: 2025-08-02 17:06:00 +0300 MSK
- 538: 2025-08-02 16:50:59 +0300 MSK
- 539: 2025-08-02 16:38:17 +0300 MSK
- 540: 2025-08-02 16:29:04 +0300 MSK
- 541: 2025-08-02 16:25:49 +0300 MSK
- 542: 2025-08-02 16:11:25 +0300 MSK
- 543: 2025-08-02 16:04:47 +0300 MSK
- 544: 2025-08-02 15:56:06 +0300 MSK
- 545: 2025-08-02 15:46:47 +0300 MSK
- 546: 2025-08-02 15:43:09 +0300 MSK
- 547: 2025-08-02 15:41:03 +0300 MSK
- 548: 2025-08-02 15:39:53 +0300 MSK
- 549: 2025-08-02 15:34:16 +0300 MSK
- 550: 2025-08-02 15:27:49 +0300 MSK
- 551: 2025-08-02 15:19:46 +0300 MSK
- 552: 2025-08-02 15:01:25 +0300 MSK
- 553: 2025-08-02 14:54:02 +0300 MSK
- 554: 2025-08-02 14:25:28 +0300 MSK
- 555: 2025-08-02 14:21:50 +0300 MSK
- 556: 2025-08-02 14:15:20 +0300 MSK
- 557: 2025-08-02 14:10:21 +0300 MSK
- 558: 2025-08-02 14:00:42 +0300 MSK
- 559: 2025-08-02 13:55:22 +0300 MSK
- 560: 2025-08-02 13:54:26 +0300 MSK
- 561: 2025-08-02 13:48:16 +0300 MSK
- 562: 2025-08-02 13:02:23 +0300 MSK
- 563: 2025-08-02 12:36:15 +0300 MSK
- 564: 2025-08-02 12:22:49 +0300 MSK
- 565: 2025-08-02 11:12:11 +0300 MSK
- 566: 2025-08-02 10:56:41 +0300 MSK
- 567: 2025-08-02 10:53:44 +0300 MSK
- 568: 2025-08-02 10:46:44 +0300 MSK
- 569: 2025-08-02 10:41:17 +0300 MSK
- 570: 2025-08-02 10:38:33 +0300 MSK
- 571: 2025-08-02 10:31:09 +0300 MSK
- 572: 2025-08-02 10:28:21 +0300 MSK
- 573: 2025-08-02 09:19:39 +0300 MSK
- 574: 2025-08-02 09:15:14 +0300 MSK
- 575: 2025-08-02 09:11:31 +0300 MSK
- 576: 2025-08-02 09:03:11 +0300 MSK
- 577: 2025-08-02 08:55:10 +0300 MSK
- 578: 2025-08-02 08:53:28 +0300 MSK
- 579: 2025-08-02 08:48:51 +0300 MSK
- 580: 2025-08-02 08:38:26 +0300 MSK
- 581: 2025-08-02 08:34:40 +0300 MSK
- 582: 2025-08-01 21:34:49 +0300 MSK
- 583: 2025-08-01 21:23:46 +0300 MSK
- 584: 2025-08-01 20:49:53 +0300 MSK
- 585: 2025-08-01 20:14:01 +0300 MSK
- 586: 2025-08-01 19:32:18 +0300 MSK
- 587: 2025-08-01 19:30:30 +0300 MSK
- 588: 2025-08-01 19:27:17 +0300 MSK
- 589: 2025-08-01 19:18:48 +0300 MSK
- 590: 2025-08-01 19:16:55 +0300 MSK
- 591: 2025-08-01 17:46:26 +0300 MSK
- 592: 2025-08-01 17:40:59 +0300 MSK
- 593: 2025-08-01 17:39:13 +0300 MSK
- 594: 2025-08-01 17:12:58 +0300 MSK
- 595: 2025-08-01 16:57:25 +0300 MSK
- 596: 2025-08-01 16:53:59 +0300 MSK
- 597: 2025-08-01 16:43:05 +0300 MSK
- 598: 2025-08-01 16:39:51 +0300 MSK
- 599: 2025-08-01 16:33:40 +0300 MSK
- 600: 2025-08-01 16:24:11 +0300 MSK
- 601: 2025-08-01 16:02:30 +0300 MSK
- 602: 2025-08-01 16:01:56 +0300 MSK
- 603: 2025-08-01 15:50:58 +0300 MSK
- 604: 2025-08-01 15:30:00 +0300 MSK
- 605: 2025-08-01 14:50:20 +0300 MSK
- 606: 2025-08-01 13:28:24 +0300 MSK
- 607: 2025-08-01 13:24:00 +0300 MSK
- 608: 2025-08-01 13:12:38 +0300 MSK
- 609: 2025-08-01 09:59:43 +0300 MSK
- 610: 2025-08-01 09:40:56 +0300 MSK
- 611: 2025-08-01 08:25:54 +0300 MSK
- 612: 2025-08-01 08:21:20 +0300 MSK
- 613: 2025-08-01 08:13:47 +0300 MSK
- 614: 2025-08-01 07:59:37 +0300 MSK
- 615: 2025-08-01 07:51:03 +0300 MSK
- 616: 2025-08-01 07:33:33 +0300 MSK
- 617: 2025-08-01 07:15:40 +0300 MSK
- 618: 2025-07-31 21:28:35 +0300 MSK
- 619: 2025-07-31 18:46:45 +0300 MSK
- 620: 2025-07-31 18:31:00 +0300 MSK
- 621: 2025-07-31 18:29:59 +0300 MSK
- 622: 2025-07-31 18:14:30 +0300 MSK
- 623: 2025-07-31 17:53:16 +0300 MSK
- 624: 2025-07-31 17:18:00 +0300 MSK
- 625: 2025-07-31 17:16:38 +0300 MSK
- 626: 2025-07-31 17:05:37 +0300 MSK
- 627: 2025-07-31 14:35:36 +0300 MSK
- 628: 2025-07-31 13:54:58 +0300 MSK
- 629: 2025-07-31 13:46:42 +0300 MSK
- 630: 2025-07-31 13:03:46 +0300 MSK
- 631: 2025-07-31 11:07:49 +0300 MSK
- 632: 2025-07-31 11:00:20 +0300 MSK
- 633: 2025-07-31 10:28:31 +0300 MSK
- 634: 2025-07-31 10:04:49 +0300 MSK
- 635: 2025-07-30 22:05:38 +0300 MSK
- 636: 2025-07-30 22:00:12 +0300 MSK
- 637: 2025-07-30 21:55:12 +0300 MSK
- 638: 2025-07-30 21:02:37 +0300 MSK
- 639: 2025-07-30 20:59:49 +0300 MSK
- 640: 2025-07-30 20:52:44 +0300 MSK
- 641: 2025-07-30 20:47:51 +0300 MSK
- 642: 2025-07-30 20:42:31 +0300 MSK
- 643: 2025-07-30 20:35:12 +0300 MSK
- 644: 2025-07-30 20:27:09 +0300 MSK
- 645: 2025-07-30 20:12:39 +0300 MSK
- 646: 2025-07-30 20:09:55 +0300 MSK
- 647: 2025-07-30 20:05:18 +0300 MSK
- 648: 2025-07-30 19:52:43 +0300 MSK
- 649: 2025-07-30 19:27:05 +0300 MSK
- 650: 2025-07-30 19:18:29 +0300 MSK
- 651: 2025-07-30 19:14:46 +0300 MSK
- 652: 2025-07-30 19:11:57 +0300 MSK
- 653: 2025-07-30 18:59:58 +0300 MSK
- 654: 2025-07-30 18:49:52 +0300 MSK
- 655: 2025-07-30 18:45:39 +0300 MSK
- 656: 2025-07-30 18:44:00 +0300 MSK
- 657: 2025-07-30 18:35:45 +0300 MSK
- 658: 2025-07-30 18:32:15 +0300 MSK
- 659: 2025-07-30 18:31:28 +0300 MSK
- 660: 2025-07-30 18:25:43 +0300 MSK
- 661: 2025-07-30 18:19:10 +0300 MSK
- 662: 2025-07-30 18:07:19 +0300 MSK
- 663: 2025-07-30 17:54:50 +0300 MSK
- 664: 2025-07-30 17:36:45 +0300 MSK
- 665: 2025-07-30 16:27:11 +0300 MSK
- 666: 2025-07-30 16:07:35 +0300 MSK
- 667: 2025-07-30 16:04:16 +0300 MSK
- 668: 2025-07-30 15:53:02 +0300 MSK
- 669: 2025-07-30 15:50:06 +0300 MSK
- 670: 2025-07-30 15:40:51 +0300 MSK
- 671: 2025-07-30 15:11:27 +0300 MSK
- 672: 2025-07-30 15:08:16 +0300 MSK
- 673: 2025-07-30 15:06:29 +0300 MSK
- 674: 2025-07-30 14:49:28 +0300 MSK
- 675: 2025-07-29 21:27:41 +0300 MSK
- 676: 2025-07-29 21:05:02 +0300 MSK
- 677: 2025-07-29 20:50:01 +0300 MSK
- 678: 2025-07-29 20:45:22 +0300 MSK
- 679: 2025-07-29 19:17:54 +0300 MSK
- 680: 2025-07-29 18:55:38 +0300 MSK
- 681: 2025-07-29 18:52:23 +0300 MSK
- 682: 2025-07-29 18:27:23 +0300 MSK
- 683: 2025-07-29 17:59:54 +0300 MSK
- 684: 2025-07-29 17:38:44 +0300 MSK
- 685: 2025-07-29 17:38:31 +0300 MSK
- 686: 2025-07-29 16:37:09 +0300 MSK
- 687: 2025-07-29 16:11:49 +0300 MSK
- 688: 2025-07-29 13:59:48 +0300 MSK
- 689: 2025-07-28 20:06:14 +0300 MSK
- 690: 2025-07-28 19:28:55 +0300 MSK
- 691: 2025-07-28 16:53:12 +0300 MSK
- 692: 2025-07-28 16:52:43 +0300 MSK
- 693: 2025-07-28 16:45:20 +0300 MSK
- 694: 2025-07-28 16:35:55 +0300 MSK
- 695: 2025-07-28 16:25:34 +0300 MSK
- 696: 2025-07-27 19:03:38 +0300 MSK
- 697: 2025-07-26 18:50:49 +0300 MSK
- 698: 2025-07-26 18:48:20 +0300 MSK
- 699: 2025-07-25 13:23:28 +0300 MSK
- 700: 2025-07-25 13:15:13 +0300 MSK
- 701: 2025-07-25 13:14:11 +0300 MSK
- 702: 2025-07-25 12:37:39 +0300 MSK
- 703: 2025-07-25 12:29:53 +0300 MSK
- 704: 2025-07-25 12:18:12 +0300 MSK
- 705: 2025-07-25 12:07:53 +0300 MSK
- 706: 2025-07-25 11:57:05 +0300 MSK
- 707: 2025-07-25 09:50:01 +0300 MSK
- 708: 2025-07-24 18:52:24 +0300 MSK
- 709: 2025-07-24 17:40:53 +0300 MSK
- 710: 2025-07-20 16:53:28 +0300 MSK
- 711: 2025-04-15 16:14:06 +0300 MSK
- 712: 2025-04-14 19:45:07 +0300 MSK
- 713: 2025-04-13 17:10:23 +0300 MSK
- 714: 2025-04-12 19:10:13 +0300 MSK
- 715: 2025-04-11 20:06:54 +0300 MSK
- 716: 2025-04-10 19:50:16 +0300 MSK
- 717: 2025-04-09 19:33:13 +0300 MSK
- 718: 2024-06-28 19:53:30 +0300 MSK
- 719: 2024-06-26 18:39:14 +0300 MSK
- 720: 2024-06-25 20:07:01 +0300 MSK
- 721: 2024-06-24 15:55:17 +0300 MSK
- 722: 2024-06-23 14:38:18 +0300 MSK
- 723: 2024-06-22 16:33:20 +0300 MSK
- 724: 2024-06-21 19:21:07 +0300 MSK
- 725: 2024-06-19 19:59:31 +0300 MSK
- 726: 2024-06-17 15:39:57 +0300 MSK
- 727: 2024-06-15 13:32:54 +0300 MSK
- 728: 2024-06-14 18:54:35 +0300 MSK
- 729: 2024-06-13 10:32:12 +0300 MSK
- 730: 2024-06-12 19:59:15 +0300 MSK
- 731: 2024-06-11 20:57:06 +0300 MSK
- 732: 2024-06-10 13:15:44 +0300 MSK
- 733: 2024-06-09 13:56:45 +0300 MSK
- 734: 2024-06-08 22:13:27 +0300 MSK
- 735: 2024-06-07 18:18:51 +0300 MSK
- 736: 2024-06-06 18:22:03 +0300 MSK
- 737: 2024-06-05 10:32:36 +0300 MSK
- 738: 2024-06-03 15:40:20 +0300 MSK
- 739: 2024-06-02 21:31:18 +0300 MSK
- 740: 2024-06-01 22:04:19 +0300 MSK
- 741: 2024-06-01 22:04:02 +0300 MSK
- 742: 2024-06-01 22:03:45 +0300 MSK
- 743: 2024-06-01 22:01:30 +0300 MSK
- 744: 2024-05-29 12:47:46 +0300 MSK
- 745: 2024-05-28 20:05:20 +0300 MSK
- 746: 2024-05-27 10:56:18 +0300 MSK
- 747: 2024-05-26 20:44:15 +0300 MSK
- 748: 2024-05-25 22:59:58 +0300 MSK
- 749: 2024-05-21 21:02:08 +0300 MSK
- 750: 2024-05-20 13:28:49 +0300 MSK
- 751: 2024-05-19 15:08:43 +0300 MSK
- 752: 2024-05-18 20:24:14 +0300 MSK
- 753: 2024-05-17 21:25:39 +0300 MSK
- 754: 2024-05-16 18:11:33 +0300 MSK
- 755: 2024-05-14 12:06:07 +0300 MSK
- 756: 2024-05-13 10:22:15 +0300 MSK
- 757: 2024-05-12 21:39:08 +0300 MSK
- 758: 2024-05-08 10:50:28 +0300 MSK
- 759: 2024-05-08 10:39:08 +0300 MSK
- 760: 2024-05-07 10:56:39 +0300 MSK
- 761: 2024-05-06 16:47:26 +0300 MSK
- 762: 2024-05-04 18:08:36 +0300 MSK
- 763: 2024-05-03 17:41:51 +0300 MSK
- 764: 2024-05-02 19:49:20 +0300 MSK
- 765: 2024-05-01 12:05:11 +0300 MSK
- 766: 2024-05-01 12:04:46 +0300 MSK
- 767: 2024-05-01 12:04:24 +0300 MSK
- 768: 2024-05-01 12:02:52 +0300 MSK
- 769: 2024-04-29 21:04:33 +0300 MSK
- 770: 2024-04-26 10:34:22 +0300 MSK
- 771: 2024-04-25 20:32:24 +0300 MSK
- 772: 2024-04-24 15:06:12 +0300 MSK
- 773: 2024-04-23 18:14:09 +0300 MSK
- 774: 2024-04-22 10:35:20 +0300 MSK
- 775: 2024-04-22 10:16:09 +0300 MSK
- 776: 2024-04-20 21:02:52 +0300 MSK
- 777: 2024-04-19 10:37:47 +0300 MSK
- 778: 2024-04-19 10:37:20 +0300 MSK
- 779: 2024-04-17 10:49:35 +0300 MSK
- 780: 2024-04-16 22:16:34 +0300 MSK
- 781: 2024-04-15 09:51:02 +0300 MSK
- 782: 2024-04-15 09:49:56 +0300 MSK
- 783: 2024-04-13 18:32:47 +0300 MSK
- 784: 2024-04-12 10:40:19 +0300 MSK
- 785: 2024-04-11 13:44:41 +0300 MSK
- 786: 2024-04-10 13:25:18 +0300 MSK
- 787: 2024-04-09 14:21:46 +0300 MSK
- 788: 2024-04-08 11:25:34 +0300 MSK
- 789: 2024-04-07 11:42:18 +0300 MSK
- 790: 2024-04-07 11:41:54 +0300 MSK
- 791: 2024-04-05 17:17:39 +0300 MSK
- 792: 2024-04-04 16:06:45 +0300 MSK
- 793: 2024-04-03 10:52:54 +0300 MSK
- 794: 2024-04-02 17:28:57 +0300 MSK
- 795: 2024-04-01 18:03:03 +0300 MSK
- 796: 2024-03-31 10:58:30 +0300 MSK
- 797: 2024-03-30 19:24:47 +0300 MSK
- 798: 2024-03-29 14:30:16 +0300 MSK
- 799: 2024-03-28 19:02:58 +0300 MSK
- 800: 2024-03-27 18:55:43 +0300 MSK
- 801: 2024-03-26 10:04:37 +0300 MSK
- 802: 2024-03-25 19:23:11 +0300 MSK
- 803: 2024-03-24 14:27:34 +0300 MSK
- 804: 2024-03-24 14:27:17 +0300 MSK
- 805: 2024-03-23 20:51:44 +0300 MSK
- 806: 2024-03-22 11:45:00 +0300 MSK
- 807: 2024-03-22 11:41:12 +0300 MSK
- 808: 2024-03-21 14:09:24 +0300 MSK
- 809: 2024-03-21 14:05:27 +0300 MSK
- 810: 2024-03-21 13:53:28 +0300 MSK
- 811: 2024-03-20 21:13:36 +0300 MSK
- 812: 2024-03-20 21:12:54 +0300 MSK
- 813: 2024-03-18 19:30:56 +0300 MSK
- 814: 2024-03-17 12:32:47 +0300 MSK
- 815: 2024-03-17 12:32:06 +0300 MSK
- 816: 2024-03-15 20:15:18 +0300 MSK
- 817: 2024-03-14 19:06:22 +0300 MSK
- 818: 2024-03-13 19:53:19 +0300 MSK
- 819: 2024-03-12 19:08:41 +0300 MSK
- 820: 2024-03-11 19:30:24 +0300 MSK
- 821: 2024-03-10 22:58:44 +0300 MSK
- 822: 2024-03-09 19:01:11 +0300 MSK
- 823: 2024-03-09 18:59:53 +0300 MSK
- 824: 2024-03-07 19:08:46 +0300 MSK
- 825: 2024-03-07 19:07:46 +0300 MSK
- 826: 2024-03-06 16:05:23 +0300 MSK
- 827: 2024-03-05 11:52:38 +0300 MSK
- 828: 2024-03-04 16:21:41 +0300 MSK
- 829: 2024-03-03 10:57:46 +0300 MSK
- 830: 2024-03-02 15:59:13 +0300 MSK
- 831: 2024-03-02 15:57:16 +0300 MSK
- 832: 2024-03-02 15:56:40 +0300 MSK
- 833: 2024-03-01 18:28:31 +0300 MSK
- 834: 2024-02-29 17:38:44 +0300 MSK
- 835: 2024-02-28 12:31:13 +0300 MSK
- 836: 2024-02-27 19:25:53 +0300 MSK
- 837: 2024-02-26 19:57:46 +0300 MSK
- 838: 2024-02-25 20:04:05 +0300 MSK
- 839: 2024-02-24 15:45:37 +0300 MSK
- 840: 2024-02-23 12:30:25 +0300 MSK
- 841: 2024-02-22 11:20:36 +0300 MSK
- 842: 2024-02-21 11:42:07 +0300 MSK
- 843: 2024-02-20 18:21:21 +0300 MSK
- 844: 2024-02-20 18:19:05 +0300 MSK
- 845: 2024-02-20 18:16:37 +0300 MSK
- 846: 2024-02-20 15:10:36 +0300 MSK
- 847: 2024-02-19 11:56:55 +0300 MSK
- 848: 2024-02-18 12:45:46 +0300 MSK
- 849: 2024-02-17 15:07:38 +0300 MSK
- 850: 2024-02-17 15:03:52 +0300 MSK
- 851: 2024-02-16 18:29:09 +0300 MSK
- 852: 2024-02-15 12:51:25 +0300 MSK
- 853: 2024-02-14 10:48:17 +0300 MSK
- 854: 2024-02-13 16:10:55 +0300 MSK
- 855: 2024-02-12 12:50:44 +0300 MSK
- 856: 2024-02-11 16:20:27 +0300 MSK
- 857: 2024-02-10 15:12:54 +0300 MSK
- 858: 2024-02-09 19:12:32 +0300 MSK
- 859: 2024-02-08 15:50:03 +0300 MSK
- 860: 2024-02-07 10:59:44 +0300 MSK
- 861: 2024-02-07 10:54:21 +0300 MSK
- 862: 2024-02-07 10:52:55 +0300 MSK
- 863: 2024-02-07 10:49:08 +0300 MSK
- 864: 2024-02-06 09:02:52 +0300 MSK
- 865: 2024-02-05 10:12:58 +0300 MSK
- 866: 2024-02-04 15:38:07 +0300 MSK
- 867: 2024-02-04 15:17:08 +0300 MSK
- 868: 2024-02-02 19:53:06 +0300 MSK
- 869: 2024-02-02 19:52:11 +0300 MSK
- 870: 2024-02-02 19:51:07 +0300 MSK
- 871: 2024-01-31 11:09:51 +0300 MSK
- 872: 2024-01-30 15:36:53 +0300 MSK
- 873: 2024-01-29 09:44:33 +0300 MSK
- 874: 2024-01-28 13:34:03 +0300 MSK
- 875: 2024-01-27 10:05:52 +0300 MSK
- 876: 2024-01-26 11:02:15 +0300 MSK
- 877: 2024-01-25 17:31:23 +0300 MSK
- 878: 2024-01-24 10:39:27 +0300 MSK
- 879: 2024-01-24 10:27:08 +0300 MSK
- 880: 2024-01-23 10:54:38 +0300 MSK
- 881: 2024-01-22 12:39:06 +0300 MSK
- 882: 2024-01-21 21:12:22 +0300 MSK
- 883: 2024-01-20 17:21:44 +0300 MSK
- 884: 2024-01-19 11:46:22 +0300 MSK
- 885: 2024-01-19 11:45:33 +0300 MSK
- 886: 2024-01-18 13:27:10 +0300 MSK
- 887: 2024-01-17 19:14:04 +0300 MSK
- 888: 2024-01-16 11:04:01 +0300 MSK
- 889: 2024-01-15 11:45:13 +0300 MSK
- 890: 2024-01-14 17:27:29 +0300 MSK
- 891: 2024-01-13 17:33:48 +0300 MSK
- 892: 2024-01-12 23:55:40 +0300 MSK
- 893: 2024-01-11 12:15:51 +0300 MSK
- 894: 2024-01-10 11:34:26 +0300 MSK
- 895: 2024-01-09 19:45:41 +0300 MSK
- 896: 2024-01-08 17:44:21 +0300 MSK
- 897: 2024-01-07 12:26:09 +0300 MSK
- 898: 2024-01-07 12:23:04 +0300 MSK
- 899: 2024-01-05 13:00:49 +0300 MSK
- 900: 2024-01-04 14:11:50 +0300 MSK
- 901: 2024-01-03 14:46:50 +0300 MSK
- 902: 2024-01-02 15:20:19 +0300 MSK
- 903: 2024-01-01 16:10:42 +0300 MSK
- 904: 2023-12-31 13:19:35 +0300 MSK
- 905: 2023-12-30 14:22:38 +0300 MSK
- 906: 2023-12-29 10:09:26 +0300 MSK
- 907: 2023-12-28 10:12:36 +0300 MSK
- 908: 2023-12-27 11:51:17 +0300 MSK
- 909: 2023-12-26 11:08:25 +0300 MSK
- 910: 2023-12-25 10:53:55 +0300 MSK
- 911: 2023-12-24 12:54:15 +0300 MSK
- 912: 2023-12-24 00:41:36 +0300 MSK
- 913: 2023-12-22 11:52:14 +0300 MSK
- 914: 2023-12-21 08:42:34 +0300 MSK
- 915: 2023-12-20 14:05:16 +0300 MSK
- 916: 2023-12-19 11:24:47 +0300 MSK
- 917: 2023-12-18 13:27:09 +0300 MSK
- 918: 2023-12-17 12:09:37 +0300 MSK
- 919: 2023-12-16 13:01:55 +0300 MSK
- 920: 2023-12-15 10:56:18 +0300 MSK
- 921: 2023-12-15 10:54:52 +0300 MSK
- 922: 2023-12-14 12:30:55 +0300 MSK
- 923: 2023-12-13 11:11:00 +0300 MSK
- 924: 2023-12-12 10:39:45 +0300 MSK
- 925: 2023-12-11 15:30:35 +0300 MSK
- 926: 2023-12-11 10:26:55 +0300 MSK
- 927: 2023-12-10 13:46:54 +0300 MSK
- 928: 2023-12-10 13:46:22 +0300 MSK
- 929: 2023-12-10 13:45:46 +0300 MSK
- 930: 2023-12-08 21:03:57 +0300 MSK
- 931: 2023-12-07 19:20:48 +0300 MSK
- 932: 2023-12-06 12:45:40 +0300 MSK
- 933: 2023-12-06 09:43:04 +0300 MSK
- 934: 2023-12-05 16:12:24 +0300 MSK
- 935: 2023-12-04 11:09:00 +0300 MSK
- 936: 2023-12-03 17:53:13 +0300 MSK
- 937: 2023-12-02 23:40:09 +0300 MSK
- 938: 2023-12-01 11:21:29 +0300 MSK
- 939: 2023-11-30 10:50:12 +0300 MSK
- 940: 2023-11-29 12:01:45 +0300 MSK
- 941: 2023-11-28 13:04:41 +0300 MSK
- 942: 2023-11-27 10:32:44 +0300 MSK
- 943: 2023-11-27 10:32:13 +0300 MSK
- 944: 2023-11-25 22:00:45 +0300 MSK
- 945: 2023-11-25 22:00:22 +0300 MSK
- 946: 2023-11-24 16:49:32 +0300 MSK
- 947: 2023-11-24 16:37:41 +0300 MSK
- 948: 2023-11-24 16:36:38 +0300 MSK
- 949: 2023-11-24 16:32:52 +0300 MSK
- 950: 2023-11-24 11:07:37 +0300 MSK
- 951: 2023-11-23 13:41:25 +0300 MSK
- 952: 2023-11-22 18:49:02 +0300 MSK
- 953: 2023-11-21 12:51:21 +0300 MSK
- 954: 2023-11-21 12:44:04 +0300 MSK
- 955: 2023-11-21 12:33:13 +0300 MSK
- 956: 2023-11-20 18:30:57 +0300 MSK
- 957: 2023-11-20 14:40:36 +0300 MSK
- 958: 2023-11-20 14:38:40 +0300 MSK
- 959: 2023-11-20 14:31:25 +0300 MSK
- 960: 2023-11-20 14:29:40 +0300 MSK
- 961: 2023-11-20 14:27:13 +0300 MSK
- 962: 2023-11-20 14:11:47 +0300 MSK
- 963: 2023-11-19 11:31:05 +0300 MSK
- 964: 2023-11-18 19:23:48 +0300 MSK
- 965: 2023-11-17 17:25:22 +0300 MSK
- 966: 2023-11-17 16:41:37 +0300 MSK
- 967: 2023-11-17 14:05:35 +0300 MSK
- 968: 2023-11-17 14:02:06 +0300 MSK
- 969: 2023-11-17 13:13:32 +0300 MSK
- 970: 2023-11-17 13:12:34 +0300 MSK
- 971: 2023-11-17 13:02:26 +0300 MSK
- 972: 2023-11-16 16:43:00 +0300 MSK
- 973: 2023-11-16 16:22:50 +0300 MSK
- 974: 2023-11-16 14:30:47 +0300 MSK
- 975: 2023-11-16 14:18:16 +0300 MSK
- 976: 2023-11-16 14:15:58 +0300 MSK
- 977: 2023-11-16 14:13:23 +0300 MSK
- 978: 2023-11-16 14:06:30 +0300 MSK
- 979: 2023-11-16 11:22:37 +0300 MSK
- 980: 2023-11-15 16:53:47 +0300 MSK
- 981: 2023-11-15 16:12:27 +0300 MSK
- 982: 2023-11-15 15:18:40 +0300 MSK
- 983: 2023-11-15 15:17:30 +0300 MSK
- 984: 2023-11-14 15:39:29 +0300 MSK
- 985: 2023-11-13 20:24:55 +0300 MSK
- 986: 2023-11-13 10:42:13 +0300 MSK
- 987: 2023-11-13 10:40:23 +0300 MSK
- 988: 2023-11-13 10:38:46 +0300 MSK
- 989: 2023-11-12 17:00:22 +0300 MSK
- 990: 2023-11-12 16:08:04 +0300 MSK
- 991: 2023-11-12 15:43:55 +0300 MSK
- 992: 2023-11-12 15:41:26 +0300 MSK
- 993: 2023-11-12 11:40:25 +0300 MSK
- 994: 2023-11-11 16:10:00 +0300 MSK
- 995: 2023-11-11 16:06:23 +0300 MSK
- 996: 2023-11-11 16:06:11 +0300 MSK
- 997: 2023-11-11 15:52:58 +0300 MSK
- 998: 2023-11-11 15:43:36 +0300 MSK
- 999: 2023-11-11 15:32:34 +0300 MSK
- 1000: 2023-11-11 15:18:39 +0300 MSK
- 1001: 2023-11-11 15:08:55 +0300 MSK
- 1002: 2023-11-11 15:06:06 +0300 MSK
- 1003: 2023-11-11 14:51:09 +0300 MSK
- 1004: 2023-11-10 19:50:03 +0300 MSK
- 1005: 2023-11-10 19:49:28 +0300 MSK
- 1006: 2023-11-10 19:47:59 +0300 MSK
- 1007: 2023-11-10 19:34:50 +0300 MSK
- 1008: 2023-11-10 19:18:28 +0300 MSK
- 1009: 2023-11-10 18:37:59 +0300 MSK
- 1010: 2023-11-10 16:30:33 +0300 MSK
- 1011: 2023-11-10 13:30:38 +0300 MSK
- 1012: 2023-11-10 13:24:56 +0300 MSK
- 1013: 2023-11-09 10:03:41 +0300 MSK
- 1014: 2023-11-08 11:09:02 +0300 MSK
- 1015: 2023-11-07 21:56:45 +0300 MSK
- 1016: 2023-11-07 21:50:49 +0300 MSK
- 1017: 2023-11-07 19:07:48 +0300 MSK
- 1018: 2023-11-06 18:41:34 +0300 MSK
- 1019: 2023-11-06 14:57:33 +0300 MSK
- 1020: 2023-11-06 14:49:27 +0300 MSK
- 1021: 2023-11-05 21:02:40 +0300 MSK
- 1022: 2023-11-05 12:06:04 +0300 MSK
- 1023: 2023-11-05 12:01:59 +0300 MSK
- 1024: 2023-11-04 13:31:04 +0300 MSK
- 1025: 2023-11-04 13:30:46 +0300 MSK
- 1026: 2023-11-04 13:30:28 +0300 MSK
- 1027: 2023-11-04 13:30:08 +0300 MSK
- 1028: 2023-11-04 13:29:52 +0300 MSK
- 1029: 2023-11-04 13:29:35 +0300 MSK
- 1030: 2023-11-04 13:29:17 +0300 MSK
- 1031: 2023-11-04 13:28:50 +0300 MSK
- 1032: 2023-11-04 13:28:04 +0300 MSK
- 1033: 2023-11-04 13:27:48 +0300 MSK
- 1034: 2023-11-04 13:27:29 +0300 MSK
- 1035: 2023-11-04 13:27:12 +0300 MSK
- 1036: 2023-11-04 13:26:43 +0300 MSK
- 1037: 2023-11-04 13:25:42 +0300 MSK
- 1038: 2023-11-04 13:25:15 +0300 MSK
- 1039: 2023-11-04 13:24:58 +0300 MSK
- 1040: 2023-11-04 13:23:30 +0300 MSK
- 1041: 2023-11-04 13:22:41 +0300 MSK
- 1042: 2023-11-04 10:36:18 +0300 MSK
- 1043: 2023-11-04 10:30:12 +0300 MSK
- 1044: 2023-11-04 10:29:26 +0300 MSK
- 1045: 2023-11-03 15:20:27 +0300 MSK
- 1046: 2023-11-03 12:40:06 +0300 MSK
- 1047: 2023-11-03 12:14:46 +0300 MSK
- 1048: 2023-11-03 12:13:05 +0300 MSK
- 1049: 2023-11-02 14:33:34 +0300 MSK
- 1050: 2023-11-02 13:32:46 +0300 MSK
- 1051: 2023-11-01 15:59:19 +0300 MSK
- 1052: 2023-11-01 15:51:19 +0300 MSK
- 1053: 2023-11-01 15:01:54 +0300 MSK
- 1054: 2023-11-01 15:00:05 +0300 MSK
- 1055: 2023-11-01 12:34:06 +0300 MSK
- 1056: 2023-11-01 12:32:26 +0300 MSK
- 1057: 2023-11-01 12:28:17 +0300 MSK
- 1058: 2023-11-01 12:20:58 +0300 MSK
- 1059: 2023-10-31 19:12:05 +0300 MSK
- 1060: 2023-10-31 19:11:41 +0300 MSK
- 1061: 2023-10-31 18:59:17 +0300 MSK
- 1062: 2023-10-31 18:18:34 +0300 MSK
- 1063: 2023-10-31 18:15:28 +0300 MSK
- 1064: 2023-10-31 18:13:57 +0300 MSK
- 1065: 2023-10-31 11:33:38 +0300 MSK
- 1066: 2023-10-31 11:32:41 +0300 MSK
- 1067: 2023-10-30 16:28:30 +0300 MSK
- 1068: 2023-10-30 16:16:38 +0300 MSK
- 1069: 2023-10-30 16:03:18 +0300 MSK
- 1070: 2023-10-30 15:58:41 +0300 MSK
- 1071: 2023-10-30 14:32:47 +0300 MSK
- 1072: 2023-10-30 14:31:36 +0300 MSK
- 1073: 2023-10-30 14:14:48 +0300 MSK
- 1074: 2023-10-30 13:59:23 +0300 MSK
- 1075: 2023-10-30 13:51:15 +0300 MSK
- 1076: 2023-10-30 13:39:35 +0300 MSK
- 1077: 2023-10-30 13:33:19 +0300 MSK
- 1078: 2023-10-30 13:26:37 +0300 MSK
- 1079: 2023-10-30 13:17:08 +0300 MSK
- 1080: 2023-10-30 13:16:47 +0300 MSK
- 1081: 2023-10-30 13:16:38 +0300 MSK
- 1082: 2023-10-30 13:13:00 +0300 MSK
- 1083: 2023-10-30 12:17:05 +0300 MSK
- 1084: 2023-10-30 12:10:35 +0300 MSK
- 1085: 2023-10-30 10:51:12 +0300 MSK
- 1086: 2023-10-29 19:36:33 +0300 MSK
- 1087: 2023-10-28 17:51:04 +0300 MSK
- 1088: 2023-10-27 17:47:50 +0300 MSK
- 1089: 2023-10-26 23:07:22 +0300 MSK
- 1090: 2023-10-25 13:37:39 +0300 MSK
- 1091: 2023-10-25 11:31:06 +0300 MSK
- 1092: 2023-10-24 14:55:16 +0300 MSK
- 1093: 2023-10-23 12:26:07 +0300 MSK
- 1094: 2023-10-22 13:57:47 +0300 MSK
- 1095: 2023-10-21 14:20:53 +0300 MSK
- 1096: 2023-10-20 16:11:39 +0300 MSK
- 1097: 2023-10-20 16:06:36 +0300 MSK
- 1098: 2023-10-19 17:09:46 +0300 MSK
- 1099: 2023-10-18 19:38:53 +0300 MSK
- 1100: 2023-10-17 18:45:21 +0300 MSK
- 1101: 2023-10-16 20:32:07 +0300 MSK
- 1102: 2023-10-15 13:05:28 +0300 MSK
- 1103: 2023-10-14 19:53:26 +0300 MSK
- 1104: 2023-10-14 10:14:40 +0300 MSK
- 1105: 2023-10-12 12:09:45 +0300 MSK
- 1106: 2023-10-11 16:06:35 +0300 MSK
- 1107: 2023-10-10 08:23:28 +0300 MSK
- 1108: 2023-10-09 14:15:25 +0300 MSK
- 1109: 2023-10-08 10:39:44 +0300 MSK
- 1110: 2023-10-07 19:48:10 +0300 MSK
- 1111: 2023-10-06 12:24:39 +0300 MSK
- 1112: 2023-10-06 12:24:09 +0300 MSK
- 1113: 2023-10-05 09:46:37 +0300 MSK
- 1114: 2023-10-04 09:00:01 +0300 MSK
- 1115: 2023-10-04 08:57:26 +0300 MSK
- 1116: 2023-10-03 09:14:03 +0300 MSK
- 1117: 2023-10-03 09:13:40 +0300 MSK
- 1118: 2023-10-03 09:13:11 +0300 MSK
- 1119: 2023-10-02 15:20:53 +0300 MSK
- 1120: 2023-10-01 16:29:08 +0300 MSK
- 1121: 2023-09-30 10:17:26 +0300 MSK
- 1122: 2023-09-30 10:09:04 +0300 MSK
- 1123: 2023-09-30 10:05:56 +0300 MSK
- 1124: 2023-09-29 08:36:09 +0300 MSK
- 1125: 2023-09-28 10:17:33 +0300 MSK
- 1126: 2023-09-28 10:13:16 +0300 MSK
- 1127: 2023-09-27 18:11:20 +0300 MSK
- 1128: 2023-09-26 13:43:09 +0300 MSK
- 1129: 2023-09-25 09:17:00 +0300 MSK
- 1130: 2023-09-25 08:28:38 +0300 MSK
- 1131: 2023-09-25 08:26:39 +0300 MSK
- 1132: 2023-09-24 14:37:54 +0300 MSK
- 1133: 2023-09-24 13:28:55 +0300 MSK
- 1134: 2023-09-24 13:26:28 +0300 MSK
- 1135: 2023-09-24 13:00:11 +0300 MSK
- 1136: 2023-09-24 12:59:51 +0300 MSK
- 1137: 2023-09-24 12:59:24 +0300 MSK
- 1138: 2023-09-24 12:56:43 +0300 MSK
- 1139: 2023-09-24 12:56:22 +0300 MSK
- 1140: 2023-09-24 12:55:57 +0300 MSK
- 1141: 2023-09-24 12:55:41 +0300 MSK
- 1142: 2023-09-24 12:55:19 +0300 MSK
- 1143: 2023-09-24 12:54:51 +0300 MSK
- 1144: 2023-09-24 12:53:12 +0300 MSK
- 1145: 2023-09-24 12:52:56 +0300 MSK
- 1146: 2023-09-24 12:52:34 +0300 MSK
- 1147: 2023-09-24 12:52:13 +0300 MSK
- 1148: 2023-09-24 12:51:48 +0300 MSK
- 1149: 2023-09-24 12:50:52 +0300 MSK
- 1150: 2023-09-24 12:50:33 +0300 MSK
- 1151: 2023-09-24 12:47:07 +0300 MSK
- 1152: 2023-09-24 12:44:33 +0300 MSK
- 1153: 2023-09-24 12:41:55 +0300 MSK
- 1154: 2023-09-24 12:41:37 +0300 MSK
- 1155: 2023-09-24 12:40:45 +0300 MSK
- 1156: 2023-09-24 12:40:14 +0300 MSK
- 1157: 2023-09-24 12:39:52 +0300 MSK
- 1158: 2023-09-24 12:38:31 +0300 MSK
- 1159: 2023-09-24 12:09:18 +0300 MSK
- 1160: 2023-09-23 21:54:59 +0300 MSK
- 1161: 2023-09-23 18:06:03 +0300 MSK
- 1162: 2023-09-23 13:19:00 +0300 MSK
- 1163: 2023-09-22 18:29:58 +0300 MSK
- 1164: 2023-09-22 13:51:50 +0300 MSK
- 1165: 2023-09-22 13:49:11 +0300 MSK
- 1166: 2023-09-22 12:14:22 +0300 MSK
- 1167: 2023-09-22 11:34:42 +0300 MSK
- 1168: 2023-09-22 11:27:41 +0300 MSK
- 1169: 2023-09-22 11:23:55 +0300 MSK
- 1170: 2023-09-22 10:24:39 +0300 MSK
- 1171: 2023-09-22 08:57:07 +0300 MSK
- 1172: 2023-09-22 08:51:25 +0300 MSK
- 1173: 2023-09-21 19:36:09 +0300 MSK
- 1174: 2023-09-21 19:11:34 +0300 MSK
- 1175: 2023-09-21 18:33:03 +0300 MSK
- 1176: 2023-09-21 09:51:52 +0300 MSK
- 1177: 2023-09-20 22:32:26 +0300 MSK
- 1178: 2023-09-20 22:28:16 +0300 MSK
- 1179: 2023-09-20 22:22:48 +0300 MSK
- 1180: 2023-09-20 22:20:17 +0300 MSK
- 1181: 2023-09-20 19:50:56 +0300 MSK
- 1182: 2023-09-20 19:35:10 +0300 MSK
- 1183: 2023-09-20 19:07:10 +0300 MSK
- 1184: 2023-09-20 18:36:36 +0300 MSK
- 1185: 2023-09-20 18:32:58 +0300 MSK
- 1186: 2023-09-20 18:32:51 +0300 MSK
- 1187: 2023-09-20 18:32:34 +0300 MSK
- 1188: 2023-09-20 18:02:39 +0300 MSK
- 1189: 2023-09-20 18:01:50 +0300 MSK
- 1190: 2023-09-20 17:28:42 +0300 MSK
- 1191: 2023-09-20 17:07:50 +0300 MSK
- 1192: 2023-09-20 16:31:32 +0300 MSK
- 1193: 2023-09-20 11:47:24 +0300 MSK
- 1194: 2023-09-19 21:08:16 +0300 MSK
- 1195: 2023-09-19 20:00:19 +0300 MSK
- 1196: 2023-09-19 19:58:37 +0300 MSK
- 1197: 2023-09-18 15:46:36 +0300 MSK
- 1198: 2023-09-18 15:46:14 +0300 MSK
- 1199: 2023-09-18 15:38:04 +0300 MSK
- 1200: 2023-09-18 15:35:47 +0300 MSK
- 1201: 2023-09-18 15:12:57 +0300 MSK
- 1202: 2023-09-18 15:12:07 +0300 MSK
- 1203: 2023-09-18 15:00:25 +0300 MSK
- 1204: 2023-09-18 14:59:16 +0300 MSK
- 1205: 2023-09-18 14:37:29 +0300 MSK
- 1206: 2023-09-18 14:34:48 +0300 MSK
- 1207: 2023-09-18 13:54:11 +0300 MSK
- 1208: 2023-09-18 09:47:53 +0300 MSK
- 1209: 2023-09-17 16:27:05 +0300 MSK
- 1210: 2023-09-17 16:16:53 +0300 MSK
- 1211: 2023-09-17 16:14:59 +0300 MSK
- 1212: 2023-09-17 16:12:53 +0300 MSK
- 1213: 2023-09-17 16:08:12 +0300 MSK
- 1214: 2023-09-17 11:45:39 +0300 MSK
- 1215: 2023-09-17 11:44:04 +0300 MSK
- 1216: 2023-09-17 11:40:01 +0300 MSK
- 1217: 2023-09-16 21:10:06 +0300 MSK
- 1218: 2023-09-16 21:07:33 +0300 MSK
- 1219: 2023-09-16 20:44:34 +0300 MSK
- 1220: 2023-09-16 20:20:21 +0300 MSK
- 1221: 2023-09-16 20:18:19 +0300 MSK
- 1222: 2023-09-16 15:46:43 +0300 MSK
- 1223: 2023-09-16 15:35:37 +0300 MSK
- 1224: 2023-09-16 15:34:15 +0300 MSK
- 1225: 2023-09-16 11:35:52 +0300 MSK
- 1226: 2023-09-16 11:25:54 +0300 MSK
- 1227: 2023-09-15 19:59:56 +0300 MSK
- 1228: 2023-09-15 19:53:02 +0300 MSK
- 1229: 2023-09-15 19:34:44 +0300 MSK
- 1230: 2023-09-15 19:33:23 +0300 MSK
- 1231: 2023-09-15 19:12:52 +0300 MSK
- 1232: 2023-09-15 19:05:16 +0300 MSK
- 1233: 2023-09-15 19:02:42 +0300 MSK
- 1234: 2023-09-15 18:53:00 +0300 MSK
- 1235: 2023-09-15 17:07:59 +0300 MSK
- 1236: 2023-09-15 12:51:11 +0300 MSK
- 1237: 2023-09-15 09:59:15 +0300 MSK
- 1238: 2023-09-14 19:02:15 +0300 MSK
- 1239: 2023-09-14 18:45:02 +0300 MSK
- 1240: 2023-09-14 18:44:27 +0300 MSK
- 1241: 2023-09-14 18:40:55 +0300 MSK
- 1242: 2023-09-14 18:08:10 +0300 MSK
- 1243: 2023-09-14 14:41:43 +0300 MSK
- 1244: 2023-09-13 19:20:05 +0300 MSK
- 1245: 2023-09-13 11:18:48 +0300 MSK
- 1246: 2023-09-12 19:36:36 +0300 MSK
- 1247: 2023-09-12 16:32:10 +0300 MSK
- 1248: 2023-09-12 15:42:35 +0300 MSK
- 1249: 2023-09-12 15:27:56 +0300 MSK
- 1250: 2023-09-12 15:23:56 +0300 MSK
- 1251: 2023-09-12 15:21:06 +0300 MSK
- 1252: 2023-09-12 14:23:58 +0300 MSK
- 1253: 2023-09-12 14:12:53 +0300 MSK
- 1254: 2023-09-12 14:07:17 +0300 MSK
- 1255: 2023-09-12 14:05:44 +0300 MSK
- 1256: 2023-09-12 14:05:12 +0300 MSK
- 1257: 2023-09-12 14:01:45 +0300 MSK
- 1258: 2023-09-12 11:17:46 +0300 MSK
- 1259: 2023-09-12 10:55:04 +0300 MSK
- 1260: 2023-09-11 19:32:16 +0300 MSK
- 1261: 2023-09-11 19:31:11 +0300 MSK
- 1262: 2023-09-11 19:16:39 +0300 MSK
- 1263: 2023-09-11 19:06:00 +0300 MSK
- 1264: 2023-09-11 18:58:15 +0300 MSK
- 1265: 2023-09-11 18:55:49 +0300 MSK
- 1266: 2023-09-11 18:46:11 +0300 MSK
- 1267: 2023-09-11 18:31:16 +0300 MSK
- 1268: 2023-09-11 18:30:56 +0300 MSK
- 1269: 2023-09-11 15:06:55 +0300 MSK
- 1270: 2023-09-10 12:48:15 +0300 MSK
- 1271: 2023-09-10 12:37:39 +0300 MSK
- 1272: 2023-09-09 20:12:03 +0300 MSK
- 1273: 2023-09-09 20:11:23 +0300 MSK
- 1274: 2023-09-09 20:10:19 +0300 MSK
- 1275: 2023-09-09 16:06:56 +0300 MSK
- 1276: 2023-09-09 10:20:58 +0300 MSK
- 1277: 2023-09-09 10:20:26 +0300 MSK
- 1278: 2023-09-08 13:41:10 +0300 MSK
- 1279: 2023-09-07 20:09:04 +0300 MSK
- 1280: 2023-09-07 20:00:09 +0300 MSK
- 1281: 2023-09-07 19:55:32 +0300 MSK
- 1282: 2023-09-07 17:13:51 +0300 MSK
- 1283: 2023-09-07 17:13:34 +0300 MSK
- 1284: 2023-09-07 17:12:50 +0300 MSK
- 1285: 2023-09-06 14:59:03 +0300 MSK
- 1286: 2023-09-05 11:41:23 +0300 MSK
- 1287: 2023-09-04 15:54:45 +0300 MSK
- 1288: 2023-09-04 12:44:01 +0300 MSK
- 1289: 2023-09-04 09:37:09 +0300 MSK
- 1290: 2023-09-03 20:06:29 +0300 MSK
- 1291: 2023-09-03 19:49:38 +0300 MSK
- 1292: 2023-09-03 11:23:58 +0300 MSK
- 1293: 2023-09-02 16:26:14 +0300 MSK
- 1294: 2023-09-02 10:50:42 +0300 MSK
- 1295: 2023-09-01 18:41:17 +0300 MSK
- 1296: 2023-09-01 18:38:28 +0300 MSK
- 1297: 2023-09-01 18:37:48 +0300 MSK
- 1298: 2023-09-01 09:58:21 +0300 MSK
- 1299: 2023-09-01 09:55:13 +0300 MSK
- 1300: 2023-08-31 22:14:58 +0300 MSK
- 1301: 2023-08-31 20:45:02 +0300 MSK
- 1302: 2023-08-31 20:35:52 +0300 MSK
- 1303: 2023-08-31 20:35:00 +0300 MSK
- 1304: 2023-08-31 20:34:31 +0300 MSK
- 1305: 2023-08-31 15:29:43 +0300 MSK
- 1306: 2023-08-31 12:14:40 +0300 MSK
- 1307: 2023-08-30 19:06:25 +0300 MSK
- 1308: 2023-08-29 19:00:49 +0300 MSK
- 1309: 2023-08-29 18:48:22 +0300 MSK
- 1310: 2023-08-29 18:48:09 +0300 MSK
- 1311: 2023-08-29 18:44:17 +0300 MSK
- 1312: 2023-08-29 18:43:22 +0300 MSK
- 1313: 2023-08-29 11:50:54 +0300 MSK
- 1314: 2023-08-28 13:37:58 +0300 MSK
- 1315: 2023-08-28 13:35:54 +0300 MSK
- 1316: 2023-08-27 18:09:36 +0300 MSK
- 1317: 2023-08-27 18:03:23 +0300 MSK
- 1318: 2023-08-27 17:55:09 +0300 MSK
- 1319: 2023-08-26 16:17:44 +0300 MSK
- 1320: 2023-08-26 16:17:28 +0300 MSK
- 1321: 2023-08-26 16:16:46 +0300 MSK
- 1322: 2023-08-26 16:06:04 +0300 MSK
- 1323: 2023-08-26 15:38:12 +0300 MSK
- 1324: 2023-08-26 15:24:31 +0300 MSK
- 1325: 2023-08-26 15:20:18 +0300 MSK
- 1326: 2023-08-26 15:20:08 +0300 MSK
- 1327: 2023-08-26 15:19:33 +0300 MSK
- 1328: 2023-08-26 15:18:57 +0300 MSK
- 1329: 2023-08-26 12:16:27 +0300 MSK
- 1330: 2023-08-25 10:04:50 +0300 MSK
- 1331: 2023-08-24 16:42:07 +0300 MSK
- 1332: 2023-08-24 13:45:42 +0300 MSK
- 1333: 2023-08-23 22:56:37 +0300 MSK
- 1334: 2023-08-23 12:45:05 +0300 MSK
- 1335: 2023-08-22 10:32:27 +0300 MSK
- 1336: 2023-08-21 23:38:46 +0300 MSK
- 1337: 2023-08-21 21:08:48 +0300 MSK
- 1338: 2023-08-21 21:08:11 +0300 MSK
- 1339: 2023-08-21 09:29:54 +0300 MSK
- 1340: 2023-08-20 14:34:41 +0300 MSK
- 1341: 2023-08-19 18:48:22 +0300 MSK
- 1342: 2023-08-19 18:13:19 +0300 MSK
- 1343: 2023-08-19 17:36:50 +0300 MSK
- 1344: 2023-08-19 17:13:39 +0300 MSK
- 1345: 2023-08-18 10:52:33 +0300 MSK
- 1346: 2023-08-17 16:52:59 +0300 MSK
- 1347: 2023-08-16 14:36:21 +0300 MSK
- 1348: 2023-08-15 17:06:49 +0300 MSK
- 1349: 2023-08-15 17:02:49 +0300 MSK
- 1350: 2023-08-14 11:17:39 +0300 MSK
- 1351: 2023-08-13 18:35:13 +0300 MSK
- 1352: 2023-08-12 17:50:41 +0300 MSK
- 1353: 2023-08-11 17:52:07 +0300 MSK
- 1354: 2023-08-11 12:05:33 +0300 MSK
- 1355: 2023-08-11 12:01:50 +0300 MSK
- 1356: 2023-08-11 11:17:35 +0300 MSK
- 1357: 2023-08-11 11:12:31 +0300 MSK
- 1358: 2023-08-10 17:04:38 +0300 MSK
- 1359: 2023-08-09 15:13:28 +0300 MSK
- 1360: 2023-08-09 12:05:47 +0300 MSK
- 1361: 2023-08-08 23:40:50 +0300 MSK
- 1362: 2023-08-08 23:36:48 +0300 MSK
- 1363: 2023-08-08 22:57:16 +0300 MSK
- 1364: 2023-08-08 22:56:36 +0300 MSK
- 1365: 2023-08-08 21:50:31 +0300 MSK
- 1366: 2023-08-08 21:27:42 +0300 MSK
- 1367: 2023-08-08 21:02:11 +0300 MSK
- 1368: 2023-08-08 20:47:19 +0300 MSK
- 1369: 2023-08-08 20:31:21 +0300 MSK
- 1370: 2023-08-08 19:53:50 +0300 MSK
- 1371: 2023-08-08 19:34:48 +0300 MSK
- 1372: 2023-08-08 14:36:45 +0300 MSK
- 1373: 2023-08-08 13:55:40 +0300 MSK
- 1374: 2023-08-08 13:55:01 +0300 MSK
- 1375: 2023-08-07 17:24:07 +0300 MSK
- 1376: 2023-08-07 14:39:05 +0300 MSK
- 1377: 2023-08-07 14:27:07 +0300 MSK
- 1378: 2023-08-07 13:27:10 +0300 MSK
- 1379: 2023-08-07 13:25:04 +0300 MSK
- 1380: 2023-08-07 13:10:04 +0300 MSK
- 1381: 2023-08-07 13:07:20 +0300 MSK
- 1382: 2023-08-07 12:57:18 +0300 MSK
- 1383: 2023-08-07 12:49:57 +0300 MSK
- 1384: 2023-08-07 12:45:54 +0300 MSK
- 1385: 2023-08-07 12:17:58 +0300 MSK
- 1386: 2023-08-06 18:05:41 +0300 MSK
- 1387: 2023-08-06 18:00:12 +0300 MSK
- 1388: 2023-08-06 17:37:57 +0300 MSK
- 1389: 2023-08-06 17:18:41 +0300 MSK
- 1390: 2023-08-05 17:53:24 +0300 MSK
- 1391: 2023-08-05 17:40:38 +0300 MSK
- 1392: 2023-08-05 12:39:41 +0300 MSK
- 1393: 2023-08-04 19:40:16 +0300 MSK
- 1394: 2023-08-04 19:38:00 +0300 MSK
- 1395: 2023-08-04 19:37:15 +0300 MSK
- 1396: 2023-08-03 12:33:31 +0300 MSK
- 1397: 2023-08-03 12:32:00 +0300 MSK
- 1398: 2023-08-02 19:02:58 +0300 MSK
- 1399: 2023-08-02 18:11:45 +0300 MSK
- 1400: 2023-08-02 17:33:24 +0300 MSK
- 1401: 2023-08-02 11:09:23 +0300 MSK
- 1402: 2023-08-02 11:07:07 +0300 MSK
- 1403: 2023-08-02 11:00:07 +0300 MSK
- 1404: 2023-08-02 10:39:16 +0300 MSK
- 1405: 2023-08-02 10:26:02 +0300 MSK
- 1406: 2023-08-01 20:38:09 +0300 MSK
- 1407: 2023-08-01 20:19:26 +0300 MSK
- 1408: 2023-08-01 18:39:03 +0300 MSK
- 1409: 2023-08-01 17:52:16 +0300 MSK
- 1410: 2023-08-01 17:35:47 +0300 MSK
- 1411: 2023-08-01 17:33:23 +0300 MSK
- 1412: 2023-08-01 17:14:55 +0300 MSK
- 1413: 2023-07-31 19:28:12 +0300 MSK
- 1414: 2023-07-31 17:17:46 +0300 MSK
- 1415: 2023-07-31 14:46:40 +0300 MSK
- 1416: 2023-07-30 20:11:15 +0300 MSK
- 1417: 2023-07-30 10:12:02 +0300 MSK
- 1418: 2023-07-29 18:54:20 +0300 MSK
- 1419: 2023-07-29 18:51:41 +0300 MSK
- 1420: 2023-07-29 13:24:33 +0300 MSK
- 1421: 2023-07-27 11:41:11 +0300 MSK
- 1422: 2023-07-27 11:39:36 +0300 MSK
- 1423: 2023-07-27 11:28:33 +0300 MSK
- 1424: 2023-07-26 22:56:56 +0300 MSK
- 1425: 2023-07-25 16:45:40 +0300 MSK
- 1426: 2023-07-25 16:38:25 +0300 MSK
- 1427: 2023-07-24 21:17:10 +0300 MSK
- 1428: 2023-07-24 21:04:18 +0300 MSK
- 1429: 2023-07-24 20:07:58 +0300 MSK
- 1430: 2023-07-24 19:52:59 +0300 MSK
- 1431: 2023-07-24 19:34:48 +0300 MSK
- 1432: 2023-07-24 19:02:15 +0300 MSK
- 1433: 2023-07-24 18:47:17 +0300 MSK
- 1434: 2023-07-24 16:56:56 +0300 MSK
- 1435: 2023-07-24 16:56:13 +0300 MSK
- 1436: 2023-07-24 16:54:39 +0300 MSK
- 1437: 2023-07-24 16:51:33 +0300 MSK
- 1438: 2023-07-24 16:49:38 +0300 MSK
- 1439: 2023-07-24 16:32:14 +0300 MSK
- 1440: 2023-07-24 16:19:40 +0300 MSK
- 1441: 2023-07-24 16:17:10 +0300 MSK
- 1442: 2023-07-24 13:04:29 +0300 MSK
- 1443: 2023-07-24 13:03:31 +0300 MSK
- 1444: 2023-07-24 12:58:41 +0300 MSK
- 1445: 2023-07-24 12:56:22 +0300 MSK
- 1446: 2023-07-24 12:44:43 +0300 MSK
- 1447: 2023-07-24 12:40:04 +0300 MSK
- 1448: 2023-07-24 11:13:00 +0300 MSK
- 1449: 2023-07-23 21:12:51 +0300 MSK
- 1450: 2023-07-23 21:01:06 +0300 MSK
- 1451: 2023-07-23 20:55:57 +0300 MSK
- 1452: 2023-07-23 20:18:00 +0300 MSK
- 1453: 2023-07-23 20:03:43 +0300 MSK
- 1454: 2023-07-23 19:57:13 +0300 MSK
- 1455: 2023-07-23 19:55:42 +0300 MSK
- 1456: 2023-07-23 16:50:34 +0300 MSK
- 1457: 2023-07-22 19:09:00 +0300 MSK
- 1458: 2023-07-22 17:36:35 +0300 MSK
- 1459: 2023-07-21 16:55:34 +0300 MSK
- 1460: 2023-07-21 16:53:22 +0300 MSK
- 1461: 2023-07-21 16:40:56 +0300 MSK
- 1462: 2023-07-21 16:40:33 +0300 MSK
- 1463: 2023-07-21 16:40:14 +0300 MSK
- 1464: 2023-07-21 16:36:57 +0300 MSK
- 1465: 2023-07-21 16:30:39 +0300 MSK
- 1466: 2023-07-21 16:20:49 +0300 MSK
- 1467: 2023-07-21 16:09:40 +0300 MSK
- 1468: 2023-07-21 16:06:08 +0300 MSK
- 1469: 2023-07-21 15:59:33 +0300 MSK
- 1470: 2023-07-21 15:52:55 +0300 MSK
- 1471: 2023-07-21 15:33:25 +0300 MSK
- 1472: 2023-07-21 13:34:45 +0300 MSK
- 1473: 2023-07-21 13:33:01 +0300 MSK
- 1474: 2023-07-21 13:26:34 +0300 MSK
- 1475: 2023-07-21 13:23:06 +0300 MSK
- 1476: 2023-07-21 13:19:55 +0300 MSK
- 1477: 2023-07-21 13:18:37 +0300 MSK
- 1478: 2023-07-21 13:11:37 +0300 MSK
- 1479: 2023-07-20 12:12:22 +0300 MSK
- 1480: 2023-07-20 11:41:51 +0300 MSK
- 1481: 2023-07-19 14:35:52 +0300 MSK
- 1482: 2023-07-19 14:26:39 +0300 MSK
- 1483: 2023-07-19 14:19:51 +0300 MSK
- 1484: 2023-07-19 14:19:26 +0300 MSK
- 1485: 2023-07-19 13:39:31 +0300 MSK
- 1486: 2023-07-19 12:33:23 +0300 MSK
- 1487: 2023-07-19 11:49:03 +0300 MSK
- 1488: 2023-07-19 11:34:17 +0300 MSK
- 1489: 2023-07-19 11:26:05 +0300 MSK
- 1490: 2023-07-19 11:25:19 +0300 MSK
- 1491: 2023-07-19 11:14:44 +0300 MSK
- 1492: 2023-07-18 18:51:03 +0300 MSK
- 1493: 2023-07-18 18:50:17 +0300 MSK
- 1494: 2023-07-18 18:39:57 +0300 MSK
- 1495: 2023-07-18 18:25:23 +0300 MSK
- 1496: 2023-07-18 18:14:47 +0300 MSK
- 1497: 2023-07-18 18:10:20 +0300 MSK
- 1498: 2023-07-18 18:02:32 +0300 MSK
- 1499: 2023-07-18 18:01:12 +0300 MSK
- 1500: 2023-07-18 17:58:35 +0300 MSK
- 1501: 2023-07-18 17:57:21 +0300 MSK
- 1502: 2023-07-18 17:10:30 +0300 MSK
- 1503: 2023-07-18 16:55:29 +0300 MSK
- 1504: 2023-07-18 16:41:40 +0300 MSK
- 1505: 2023-07-18 16:37:43 +0300 MSK
- 1506: 2023-07-18 16:15:43 +0300 MSK
- 1507: 2023-07-18 15:49:17 +0300 MSK
- 1508: 2023-07-18 15:46:05 +0300 MSK
- 1509: 2023-07-18 15:23:22 +0300 MSK
- 1510: 2023-07-18 15:15:34 +0300 MSK
- 1511: 2023-07-18 15:08:44 +0300 MSK
- 1512: 2023-07-18 14:53:17 +0300 MSK
- 1513: 2023-07-18 14:46:38 +0300 MSK
- 1514: 2023-07-18 13:48:20 +0300 MSK
- 1515: 2023-07-16 19:26:31 +0300 MSK
- 1516: 2023-07-16 19:19:33 +0300 MSK
- 1517: 2023-07-16 18:35:46 +0300 MSK
- 1518: 2023-07-16 15:06:38 +0300 MSK
- 1519: 2023-07-16 15:04:36 +0300 MSK
- 1520: 2023-07-16 13:34:50 +0300 MSK
- 1521: 2023-07-16 12:53:42 +0300 MSK
- 1522: 2023-07-16 12:51:01 +0300 MSK
- 1523: 2023-07-16 12:38:36 +0300 MSK
- 1524: 2023-07-16 12:17:02 +0300 MSK
- 1525: 2023-07-16 12:16:10 +0300 MSK
- 1526: 2023-07-16 10:47:21 +0300 MSK
- 1527: 2023-07-16 10:41:43 +0300 MSK
- 1528: 2023-07-16 10:41:26 +0300 MSK
- 1529: 2023-07-15 21:24:48 +0300 MSK
- 1530: 2023-07-15 21:22:16 +0300 MSK
- 1531: 2023-07-15 21:11:36 +0300 MSK
- 1532: 2023-07-15 20:53:31 +0300 MSK
- 1533: 2023-07-15 20:49:31 +0300 MSK
- 1534: 2023-07-15 20:05:44 +0300 MSK
- 1535: 2023-07-15 19:55:32 +0300 MSK
- 1536: 2023-07-15 19:35:16 +0300 MSK
- 1537: 2023-07-13 21:11:33 +0300 MSK
- 1538: 2023-07-13 20:57:51 +0300 MSK
- 1539: 2023-07-13 20:49:03 +0300 MSK
- 1540: 2023-07-13 20:34:54 +0300 MSK
- 1541: 2023-07-13 20:32:03 +0300 MSK
- 1542: 2023-07-13 20:30:18 +0300 MSK
- 1543: 2023-07-13 20:19:45 +0300 MSK
- 1544: 2023-07-13 19:37:36 +0300 MSK
- 1545: 2023-07-13 19:13:31 +0300 MSK
- 1546: 2023-07-13 19:03:15 +0300 MSK
- 1547: 2023-07-13 18:52:44 +0300 MSK
- 1548: 2023-07-13 18:46:43 +0300 MSK
- 1549: 2023-07-12 20:34:00 +0300 MSK
- 1550: 2023-07-11 17:42:28 +0300 MSK
- 1551: 2023-07-11 17:40:20 +0300 MSK
- 1552: 2023-07-10 15:59:08 +0300 MSK
- 1553: 2023-07-10 15:57:30 +0300 MSK
- 1554: 2023-07-10 15:49:18 +0300 MSK
- 1555: 2023-07-08 18:57:18 +0300 MSK
- 1556: 2023-07-08 18:48:01 +0300 MSK
- 1557: 2023-07-08 18:25:39 +0300 MSK
- 1558: 2023-07-06 20:44:21 +0300 MSK
- 1559: 2023-07-06 15:43:40 +0300 MSK
- 1560: 2023-05-24 13:25:03 +0300 MSK
- 1561: 2023-05-24 13:11:40 +0300 MSK
- 1562: 2023-05-24 12:54:30 +0300 MSK
- 1563: 2023-05-24 12:13:29 +0300 MSK
- 1564: 2023-05-24 11:52:15 +0300 MSK
- 1565: 2023-05-24 11:37:01 +0300 MSK
- 1566: 2023-05-24 11:26:20 +0300 MSK
- 1567: 2023-05-24 11:15:01 +0300 MSK
- 1568: 2023-05-23 12:36:30 +0300 MSK
- 1569: 2023-05-23 12:30:44 +0300 MSK
- 1570: 2022-05-17 07:59:02 +0300 MSK
- 1571: 2022-05-15 18:44:33 +0300 MSK
- 1572: 2022-05-14 15:28:36 +0300 MSK
- 1573: 2022-05-13 07:19:10 +0300 MSK
- 1574: 2022-05-13 07:17:45 +0300 MSK
- 1575: 2022-05-12 18:05:33 +0300 MSK
- 1576: 2022-05-11 18:03:06 +0300 MSK
- 1577: 2022-05-08 17:27:21 +0300 MSK
- 1578: 2022-05-07 13:44:16 +0300 MSK
- 1579: 2022-05-07 13:05:13 +0300 MSK
- 1580: 2022-05-06 20:02:58 +0300 MSK
- 1581: 2022-05-06 19:50:38 +0300 MSK
- 1582: 2022-05-06 19:25:00 +0300 MSK
- 1583: 2022-05-05 18:39:53 +0300 MSK
- 1584: 2022-05-05 18:26:39 +0300 MSK
- 1585: 2022-05-05 15:37:11 +0300 MSK
- 1586: 2022-05-05 15:10:54 +0300 MSK
- 1587: 2022-05-05 13:50:33 +0300 MSK
- 1588: 2022-05-05 13:43:47 +0300 MSK
- 1589: 2022-05-05 13:39:30 +0300 MSK
- 1590: 2022-05-05 13:39:06 +0300 MSK
- 1591: 2022-05-05 13:38:25 +0300 MSK
- 1592: 2022-05-05 13:32:58 +0300 MSK
- 1593: 2022-05-05 13:14:51 +0300 MSK
- 1594: 2022-05-05 07:01:33 +0300 MSK
- 1595: 2022-05-04 13:13:54 +0300 MSK
- 1596: 2022-05-04 12:54:11 +0300 MSK
- 1597: 2022-05-04 12:36:38 +0300 MSK
- 1598: 2022-05-04 08:33:36 +0300 MSK
- 1599: 2022-05-04 08:32:16 +0300 MSK
- 1600: 2022-05-04 08:30:20 +0300 MSK
- 1601: 2022-05-04 07:34:24 +0300 MSK
- 1602: 2022-05-04 07:03:31 +0300 MSK
- 1603: 2022-05-04 06:39:29 +0300 MSK
- 1604: 2022-05-04 06:26:24 +0300 MSK
- 1605: 2022-05-04 05:57:55 +0300 MSK
- 1606: 2022-05-04 05:49:11 +0300 MSK
- 1607: 2022-05-03 18:34:04 +0300 MSK
- 1608: 2022-05-03 17:44:29 +0300 MSK
- 1609: 2022-05-03 17:39:58 +0300 MSK
- 1610: 2022-05-03 15:28:52 +0300 MSK
- 1611: 2022-05-03 15:08:53 +0300 MSK
- 1612: 2022-05-03 15:05:02 +0300 MSK
- 1613: 2022-05-03 13:17:41 +0300 MSK
- 1614: 2022-05-03 13:17:21 +0300 MSK
- 1615: 2022-05-02 19:07:40 +0300 MSK
- 1616: 2022-05-02 18:49:07 +0300 MSK
- 1617: 2022-05-02 18:02:36 +0300 MSK
- 1618: 2022-05-02 17:51:33 +0300 MSK
- 1619: 2022-05-02 17:49:22 +0300 MSK
- 1620: 2022-05-02 17:34:04 +0300 MSK
- 1621: 2022-05-02 16:35:35 +0300 MSK
- 1622: 2022-05-02 16:28:49 +0300 MSK
- 1623: 2022-05-02 14:58:45 +0300 MSK
- 1624: 2022-05-02 07:24:29 +0300 MSK
- 1625: 2022-05-01 16:23:58 +0300 MSK
- 1626: 2022-05-01 15:41:08 +0300 MSK
- 1627: 2022-05-01 13:28:32 +0300 MSK
- 1628: 2022-05-01 13:12:45 +0300 MSK
- 1629: 2022-05-01 09:06:49 +0300 MSK
- 1630: 2022-04-30 22:06:12 +0300 MSK
- 1631: 2022-04-30 20:27:04 +0300 MSK
- 1632: 2022-04-30 18:34:48 +0300 MSK
- 1633: 2022-04-30 09:12:31 +0300 MSK
- 1634: 2022-04-30 08:49:48 +0300 MSK
- 1635: 2022-04-30 08:49:00 +0300 MSK
- 1636: 2022-04-30 08:30:40 +0300 MSK
- 1637: 2022-04-30 07:52:06 +0300 MSK
- 1638: 2022-04-30 06:41:23 +0300 MSK
- 1639: 2022-04-30 06:29:16 +0300 MSK
- 1640: 2022-04-30 05:36:04 +0300 MSK
- 1641: 2022-04-29 22:10:38 +0300 MSK
- 1642: 2022-04-29 19:52:46 +0300 MSK
- 1643: 2022-04-29 18:51:04 +0300 MSK
- 1644: 2022-04-29 18:09:02 +0300 MSK
- 1645: 2022-04-28 09:04:20 +0300 MSK
- 1646: 2022-04-28 08:59:35 +0300 MSK
- 1647: 2022-04-28 08:59:06 +0300 MSK
- 1648: 2022-04-28 08:55:16 +0300 MSK
1 - 2025-09-22 19:34:44 +0300 MSK
Count Elements With Maximum Frequency
Links
Code
class Solution:
def maxFrequencyElements(self, nums: List[int]) -> int:
max_freq, max_freq_count = 0, 0
freqs = [0] * 101
for num in nums:
freqs[num] += 1
for num, freq in enumerate(freqs):
if freq > max_freq:
max_freq, max_freq_count = freq, freq
elif freq == max_freq:
max_freq_count += freq
return max_freq_count
2 - 2025-09-21 19:30:58 +0300 MSK
Design Movie Rental System
Links
Code
class MovieRentingSystem:
def __init__(self, n: int, entries: List[List[int]]):
self.available = {} # (shop, movie) -> price
self.movie_shops = {} # movie -> list of (price, shop)
self.rented = set() # (shop, movie) that are currently rented
for shop, movie, price in entries:
self.available[(shop, movie)] = price
if movie not in self.movie_shops:
self.movie_shops[movie] = []
self.movie_shops[movie].append((price, shop))
# Sort shops by price for each movie initially
for movie in self.movie_shops:
self.movie_shops[movie].sort()
def search(self, movie: int) -> List[int]:
result = []
for price, shop in self.movie_shops.get(movie, []):
if (shop, movie) not in self.rented:
result.append(shop)
if len(result) == 5:
break
return result
def rent(self, shop: int, movie: int) -> None:
self.rented.add((shop, movie))
def drop(self, shop: int, movie: int) -> None:
self.rented.discard((shop, movie))
def report(self) -> List[List[int]]:
rented_list = []
for shop, movie in self.rented:
price = self.available[(shop, movie)]
rented_list.append((price, shop, movie))
rented_list.sort()
return [[shop, movie] for price, shop, movie in rented_list[:5]]
3 - 2025-09-20 19:25:16 +0300 MSK
Implement Router
Links
Code
class Router:
def __init__(self, memoryLimit: int):
self.size = memoryLimit
self.packets = {} # key -> [source, destination, timestamp]
self.counts = defaultdict(list) # destination -> sorted list of timestamps
self.queue = deque() # FIFO order of packets
def addPacket(self, source: int, destination: int, timestamp: int) -> bool:
key = self._encode(source, destination, timestamp)
# Duplicate check
if key in self.packets:
return False
# If memory full, forward oldest packet
if len(self.packets) >= self.size:
self.forwardPacket()
# Add packet
self.packets[key] = [source, destination, timestamp]
self.queue.append(key)
self.counts[destination].append(timestamp)
return True
def forwardPacket(self):
if not self.packets:
return []
key = self.queue.popleft()
packet = self.packets.pop(key)
dest = packet[1]
self.counts[dest].pop(0) # remove the earliest timestamp
return packet
def getCount(self, destination: int, startTime: int, endTime: int) -> int:
timestamps = self.counts.get(destination, [])
if not timestamps:
return 0
# Binary search for range
left = bisect.bisect_left(timestamps, startTime)
right = bisect.bisect_right(timestamps, endTime)
return right - left
def _encode(self, source: int, destination: int, timestamp: int) -> int:
# Encode uniquely into 1 number
return (source << 40) | (destination << 20) | timestamp
4 - 2025-09-19 18:44:46 +0300 MSK
Design Spreadsheet
Links
Code
class Spreadsheet:
def __init__(self, rows: int):
self._grid = [[0] * 26 for _ in range(rows)]
def _coord(self, cell: str) -> tuple[int, int]:
return int(cell[1:]) - 1, ord(cell[0]) - ord("A")
def setCell(self, cell: str, value: int) -> None:
row, col = self._coord(cell)
self._grid[row][col] = value
def resetCell(self, cell: str) -> None:
row, col = self._coord(cell)
self._grid[row][col] = 0
def getValue(self, formula: str) -> int:
res = 0
for cell in formula[1:].split("+"):
if cell[0].isdigit():
res += int(cell)
else:
row, col = self._coord(cell)
res += self._grid[row][col]
return res
# Your Spreadsheet object will be instantiated and called as such:
# obj = Spreadsheet(rows)
# obj.setCell(cell,value)
# obj.resetCell(cell)
# param_3 = obj.getValue(formula)
5 - 2025-09-18 19:58:25 +0300 MSK
Design Task Manager
Links
Code
class TaskManager:
def __init__(self, tasks: List[List[int]]):
self.tasks = SortedSet()
self.task_to_users = {}
self.task_to_priority = {}
for user_id, task_id, priority in tasks:
self.add(user_id, task_id, priority)
def add(self, userId: int, taskId: int, priority: int) -> None:
self.tasks.add((priority, taskId, userId))
self.task_to_users[taskId] = userId
self.task_to_priority[taskId] = priority
def edit(self, taskId: int, newPriority: int) -> None:
user = self.task_to_users[taskId]
self.rmv(taskId)
self.add(user, taskId, newPriority)
def rmv(self, taskId: int) -> None:
user = self.task_to_users[taskId]
priority = self.task_to_priority[taskId]
self.tasks.remove((priority, taskId, user))
del self.task_to_users[taskId]
del self.task_to_priority[taskId]
def execTop(self) -> int:
if not self.tasks:
return -1
_, task_id, user_id = self.tasks[-1]
self.rmv(task_id)
return user_id
6 - 2025-09-17 20:39:54 +0300 MSK
Design a Food Rating System
Links
Code
from sortedcontainers import SortedSet
class FoodRatings:
def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
# Map food with its rating.
self.food_rating_map = {}
# Map food with the cuisine it belongs to.
self.food_cuisine_map = {}
# Store all food of cuisine in a set (to sort them on ratings/name)
# Set element -> Tuple: (-1 * food_rating, food_name)
self.cuisine_food_map = defaultdict(SortedSet)
for i in range(len(foods)):
# Store 'rating' and 'cuisine' of the current 'food' in 'food_rating_map' and 'food_cuisine_map' maps.
self.food_rating_map[foods[i]] = ratings[i]
self.food_cuisine_map[foods[i]] = cuisines[i]
# Insert the '(-1 * rating, name)' element in the current cuisine's set.
self.cuisine_food_map[cuisines[i]].add((-ratings[i], foods[i]))
def changeRating(self, food: str, newRating: int) -> None:
# Fetch cuisine name for food.
cuisine_name = self.food_cuisine_map[food]
# Find and delete the element from the respective cuisine's set.
old_element = (-self.food_rating_map[food], food)
self.cuisine_food_map[cuisine_name].remove(old_element)
# Update food's rating in 'food_rating' map.
self.food_rating_map[food] = newRating
# Insert the '(-1 * new rating, name)' element in the respective cuisine's set.
self.cuisine_food_map[cuisine_name].add((-newRating, food))
def highestRated(self, cuisine: str) -> str:
highest_rated = self.cuisine_food_map[cuisine][0]
# Return name of the highest-rated 'food' of 'cuisine'.
return highest_rated[1]
7 - 2025-09-16 18:41:40 +0300 MSK
Replace Non-Coprime Numbers in Array
Links
Code
from math import gcd
class Solution(object):
def replaceNonCoprimes(self, nums):
stack = []
for num in nums:
while stack:
g = gcd(stack[-1], num)
if g == 1:
break
num = (stack.pop() * num) // g
stack.append(num)
return stack
8 - 2025-09-15 18:04:52 +0300 MSK
Maximum Number of Words You Can Type
Links
Code
class Solution:
def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
ignore = False
res = 0
for char in itertools.chain(text, " "):
if char == " ":
if ignore:
ignore = False
else:
res += 1
elif char in brokenLetters:
ignore = True
return res
9 - 2025-09-14 19:11:43 +0300 MSK
Vowel Spellchecker
Links
Code
class Solution(object):
def spellchecker(self, wordlist, queries):
def devowel(word):
return "".join('*' if c in 'aeiou' else c
for c in word)
words_perfect = set(wordlist)
words_cap = {}
words_vow = {}
for word in wordlist:
wordlow = word.lower()
words_cap.setdefault(wordlow, word)
words_vow.setdefault(devowel(wordlow), word)
def solve(query):
if query in words_perfect:
return query
queryL = query.lower()
if queryL in words_cap:
return words_cap[queryL]
queryLV = devowel(queryL)
if queryLV in words_vow:
return words_vow[queryLV]
return ""
return tuple(map(solve, queries))
10 - 2025-09-13 18:48:49 +0300 MSK
Find Most Frequent Vowel and Consonant
Links
Code
class Solution:
def maxFreqSum(self, s: str) -> int:
freqs = [0] * 26
for char in s:
freqs[ord(char) - 97] += 1
max_vow, max_con = 0, 0
for i in range(26):
if chr(i + 97) in ("a", "e", "i", "o", "u"):
max_vow = max(max_vow, freqs[i])
else:
max_con = max(max_con, freqs[i])
return max_vow + max_con
11 - 2025-09-12 21:22:49 +0300 MSK
Vowels Game in a String
Links
Code
class Solution:
def doesAliceWin(self, s: str) -> bool:
return any(c in "aeiou" for c in s)
12 - 2025-09-11 20:29:02 +0300 MSK
Sort Vowels in a String
Links
Code
class Solution:
def sortVowels(self, s: str) -> str:
vowels = []
s_list = list(s)
# collect all vowels
for i in s_list:
if i in "AEIOUaeiou":
vowels.append(i)
if vowels == []:
return s
# sort the vowels
vowels.sort()
count = 0
# replace original vowels with sorted ones
for j in range(len(s)):
if s_list[j] in "AEIOUaeiou":
s_list[j] = vowels[count]
count += 1
return "".join(s_list)
13 - 2025-09-10 18:11:04 +0300 MSK
Minimum Number of People to Teach
Links
Code
class Solution:
def minimumTeachings(
self, n: int, languages: List[List[int]], friendships: List[List[int]]
) -> int:
cncon = set()
for friendship in friendships:
mp = {}
conm = False
for lan in languages[friendship[0] - 1]:
mp[lan] = 1
for lan in languages[friendship[1] - 1]:
if lan in mp:
conm = True
break
if not conm:
cncon.add(friendship[0] - 1)
cncon.add(friendship[1] - 1)
max_cnt = 0
cnt = [0] * (n + 1)
for friendship in cncon:
for lan in languages[friendship]:
cnt[lan] += 1
max_cnt = max(max_cnt, cnt[lan])
return len(cncon) - max_cnt
14 - 2025-09-09 18:44:51 +0300 MSK
Number of People Aware of a Secret
Links
Code
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
know, share = deque([(1, 1)]), deque([])
know_cnt, share_cnt = 1, 0
for i in range(2, n + 1):
if know and know[0][0] == i - delay:
know_cnt -= know[0][1]
share_cnt += know[0][1]
share.append(know[0])
know.popleft()
if share and share[0][0] == i - forget:
share_cnt -= share[0][1]
share.popleft()
if share:
know_cnt += share_cnt
know.append((i, share_cnt))
return (know_cnt + share_cnt) % (10**9 + 7)
15 - 2025-09-08 18:09:53 +0300 MSK
Convert Integer to the Sum of Two No-Zero Integers
Links
Code
class Solution:
def getNoZeroIntegers(self, n: int) -> List[int]:
for A in range(1, n):
B = n - A
if "0" not in str(A) + str(B):
return [A, B]
return []
16 - 2025-09-07 11:16:52 +0300 MSK
Minimum Operations to Equalize Array
Links
Code
class Solution:
def minOperations(self, nums: List[int]) -> int:
num1 = nums[0]
for num in nums[1:]:
if num != num1:
return 1
return 0
17 - 2025-09-07 11:00:41 +0300 MSK
Find N Unique Integers Sum up to Zero
Links
Code
class Solution:
def sumZero(self, n: int) -> List[int]:
res = []
for i in range(1, n, 2):
res.extend((i, -i))
if len(res) < n:
res.append(0)
return res
18 - 2025-09-06 17:38:19 +0300 MSK
Minimum Operations to Make Array Elements Zero
Links
Code
class Solution:
def get(self, num: int) -> int:
i = 1
base = 1
cnt = 0
while base <= num:
cnt += ((i + 1) // 2) * (min(base * 2 - 1, num) - base + 1)
i += 1
base *= 2
return cnt
def minOperations(self, queries: List[List[int]]) -> int:
res = 0
for q in queries:
res += (self.get(q[1]) - self.get(q[0] - 1) + 1) // 2
return res
19 - 2025-09-05 19:23:51 +0300 MSK
Minimum Operations to Make the Integer Zero
Links
Code
class Solution:
def makeTheIntegerZero(self, num1: int, num2: int) -> int:
k = 1
while True:
x = num1 - num2 * k
if x < k:
return -1
if k >= x.bit_count():
return k
k += 1
20 - 2025-09-04 22:15:30 +0300 MSK
Find Closest Person
Links
Code
class Solution:
def findClosest(self, x: int, y: int, z: int) -> int:
dxz = abs(x - z)
dyz = abs(y - z)
if dxz < dyz:
return 1
elif dxz > dyz:
return 2
else:
return 0
21 - 2025-09-03 18:20:51 +0300 MSK
Find the Number of Ways to Place People II
Links
Code
class Solution:
def numberOfPairs(self, points: List[List[int]]) -> int:
ans = 0
points.sort(key=lambda x: (x[0], -x[1]))
for i in range(len(points) - 1):
pointA = points[i]
xMin = pointA[0] - 1
xMax = math.inf
yMin = -math.inf
yMax = pointA[1] + 1
for j in range(i + 1, len(points)):
pointB = points[j]
if (
pointB[0] > xMin
and pointB[0] < xMax
and pointB[1] > yMin
and pointB[1] < yMax
):
ans += 1
xMin = pointB[0]
yMin = pointB[1]
return ans
22 - 2025-09-02 20:18:23 +0300 MSK
Find the Number of Ways to Place People I
Links
Code
class Solution:
def numberOfPairs(self, points: List[List[int]]) -> int:
ans = 0
n = len(points)
for i in range(n):
pointA = points[i]
for j in range(n):
pointB = points[j]
if i == j or not (
pointA[0] <= pointB[0] and pointA[1] >= pointB[1]
):
continue
if n == 2:
ans += 1
continue
illegal = False
for k in range(n):
if k == i or k == j:
continue
pointTmp = points[k]
isXContained = (
pointTmp[0] >= pointA[0] and pointTmp[0] <= pointB[0]
)
isYContained = (
pointTmp[1] <= pointA[1] and pointTmp[1] >= pointB[1]
)
if isXContained and isYContained:
illegal = True
break
if not illegal:
ans += 1
return ans
23 - 2025-09-01 17:35:05 +0300 MSK
Maximum Average Pass Ratio
Links
Code
class Solution:
def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
n = len(classes)
res = 0
for i in range(n):
pass_, total = classes[i]
profit = ((pass_ + 1) / (total + 1)) - (pass_ / total)
classes[i] = (-profit, pass_, total)
heapq.heapify(classes)
while classes and extraStudents > 0:
_, pass_, total = heapq.heappop(classes)
if pass_ == total:
res += 1
else:
pass_ += 1
total += 1
profit = ((pass_ + 1) / (total + 1)) - (pass_ / total)
heapq.heappush(classes, (-profit, pass_, total))
extraStudents -= 1
for _, pass_, total in classes:
res += pass_ / total
return res / n
24 - 2025-08-31 15:07:32 +0300 MSK
Sudoku Solver
Links
Code
class Solution:
def solveSudoku(self, board: list[list[str]]) -> None:
n, N = 3, 9
rows = [[0] * (N + 1) for _ in range(N)]
cols = [[0] * (N + 1) for _ in range(N)]
boxes = [[0] * (N + 1) for _ in range(N)]
sudokuSolved = False
def couldPlace(d, row, col):
idx = (row // n) * n + col // n
return (rows[row][d] + cols[col][d] + boxes[idx][d]) == 0
def placeNumber(d, row, col):
idx = (row // n) * n + col // n
rows[row][d] += 1
cols[col][d] += 1
boxes[idx][d] += 1
board[row][col] = str(d)
def removeNumber(d, row, col):
idx = (row // n) * n + col // n
rows[row][d] -= 1
cols[col][d] -= 1
boxes[idx][d] -= 1
board[row][col] = '.'
def placeNextNumbers(row, col):
nonlocal sudokuSolved
if row == N - 1 and col == N - 1:
sudokuSolved = True
elif col == N - 1:
backtrack(row + 1, 0)
else:
backtrack(row, col + 1)
def backtrack(row, col):
nonlocal sudokuSolved
if board[row][col] == '.':
for d in range(1, 10):
if couldPlace(d, row, col):
placeNumber(d, row, col)
placeNextNumbers(row, col)
if not sudokuSolved:
removeNumber(d, row, col)
else:
placeNextNumbers(row, col)
for i in range(N):
for j in range(N):
if board[i][j] != '.':
placeNumber(int(board[i][j]), i, j)
backtrack(0, 0)
25 - 2025-08-31 14:18:46 +0300 MSK
Restore Finishing Order
Links
Code
class Solution:
def recoverOrder(self, order: List[int], friends: List[int]) -> List[int]:
for i in range(len(order)):
if order[i] in friends:
order[i] = (i, order[i])
else:
order[i] = (101, 101)
order.sort()
while order[-1] == (101, 101):
order.pop()
for i in range(len(order)):
order[i] = order[i][1]
return order
26 - 2025-08-31 14:13:40 +0300 MSK
Find The Least Frequent Digit
Links
Code
class Solution:
def getLeastFrequentDigit(self, n: int) -> int:
freqs = [0] * 10
while n > 0:
freqs[n % 10] += 1
n //= 10
min_freq, min_num = math.inf, -math.inf
for i in range(10):
if freqs[i] != 0 and (
freqs[i] < min_freq or (freqs[i] == min_freq and i < min_num)
):
min_freq, min_num = freqs[i], i
return min_num
27 - 2025-08-30 20:16:00 +0300 MSK
Valid Sudoku
Links
Code
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = [[False] * 9 for _ in range(9)]
cols = [[False] * 9 for _ in range(9)]
boxes = [[False] * 9 for _ in range(9)]
for i in range(9):
for j in range(9):
if board[i][j] != '.':
num = ord(board[i][j]) - ord('1')
boxIndex = (i // 3) * 3 + (j // 3)
if rows[i][num] or cols[j][num] or boxes[boxIndex][num]:
return False
rows[i][num] = cols[j][num] = boxes[boxIndex][num] = True
return True
28 - 2025-08-29 19:59:52 +0300 MSK
Alice and Bob Playing Flower Game
Links
Code
class Solution:
def flowerGame(self, n: int, m: int) -> int:
return (m * n) // 2
29 - 2025-08-28 16:59:23 +0300 MSK
Sort Matrix by Diagonals
Links
Code
class Solution:
def sortMatrix(self, grid: List[List[int]]) -> List[List[int]]:
n = len(grid)
for i in range(n):
tmp = [grid[i + j][j] for j in range(n - i)]
tmp.sort(reverse=True)
for j in range(n - i):
grid[i + j][j] = tmp[j]
for j in range(1, n):
tmp = [grid[i][j + i] for i in range(n - j)]
tmp.sort()
for i in range(n - j):
grid[i][j + i] = tmp[i]
return grid
30 - 2025-08-27 16:22:50 +0300 MSK
Length of Longest V-Shaped Diagonal Segment
Links
Code
class Solution:
def lenOfVDiagonal(self, grid: List[List[int]]) -> int:
DIRS = [(1, 1), (1, -1), (-1, -1), (-1, 1)]
m, n = len(grid), len(grid[0])
@cache
def dfs(cx, cy, direction, turn, target):
nx, ny = cx + DIRS[direction][0], cy + DIRS[direction][1]
# If it goes beyond the boundary or the next node's value is not the target value, then return
if nx < 0 or ny < 0 or nx >= m or ny >= n or grid[nx][ny] != target:
return 0
turn_int = 1 if turn else 0
# Continue walking in the original direction.
max_step = dfs(nx, ny, direction, turn, 2 - target)
if turn:
# Clockwise rotate 90 degrees turn
max_step = max(
max_step,
dfs(nx, ny, (direction + 1) % 4, False, 2 - target),
)
return max_step + 1
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
for direction in range(4):
res = max(res, dfs(i, j, direction, True, 2) + 1)
return res
31 - 2025-08-26 09:10:25 +0300 MSK
String to Integer (atoi)
Links
Code
class Solution:
def myAtoi(self, s: str) -> int:
digits = []
sign = None
found_dig = False
for char in s:
if char.isdigit():
digits.append(int(char))
found_dig = True
elif not found_dig and sign is None and char == " ":
continue
elif not found_dig and sign is None and char in ("+", "-"):
sign = 1
if char == "-":
sign = -1
else:
break
if sign is None:
sign = 1
res = 0
cnt = 0
while digits:
res += digits.pop() * (10 ** cnt)
cnt += 1
if res > 2 ** 31 - 1 and sign == 1:
return 2 ** 31 - 1
elif res > 2 ** 31 and sign == -1:
return -(2 ** 31)
return res * sign
32 - 2025-08-26 08:16:39 +0300 MSK
Reverse Integer
Links
Code
class Solution:
def reverse(self, x: int) -> int:
digits = []
neg = 1
if x < 0:
neg = -1
x = -x
while x > 0:
digits.append(x % 10)
x //= 10
cnt, res = 0, 0
while digits:
res += digits.pop() * (10 ** cnt)
cnt += 1
if res > 2 ** 31:
return 0
return res * neg
33 - 2025-08-26 08:11:15 +0300 MSK
Maximum Area of Longest Diagonal Rectangle
Links
Code
class Solution:
def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int:
max_diag, max_area = 0, 0
for ln, wdth in dimensions:
diag, area = ln ** 2 + wdth ** 2, ln * wdth
if diag > max_diag or (diag == max_diag and area > max_area):
max_diag, max_area = diag, area
return max_area
34 - 2025-08-25 17:00:38 +0300 MSK
My Calendar I
Links
Code
class MyCalendar:
def __init__(self):
self.events = SortedList()
def book(self, startTime: int, endTime: int) -> bool:
insert_index = self.events.bisect_left((startTime, endTime))
if (
insert_index - 1 >= 0
and startTime < self.events[insert_index - 1][1]
) or (
insert_index < len(self.events)
and self.events[insert_index][0] < endTime
):
return False
self.events.add((startTime, endTime))
return True
# Your MyCalendar object will be instantiated and called as such:
# obj = MyCalendar()
# param_1 = obj.book(startTime,endTime)
35 - 2025-08-25 11:40:44 +0300 MSK
Diagonal Traverse
Links
Code
class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
res, rows, cols, cur = [], len(mat), len(mat[0]), []
for i in range(rows + cols):
if i < rows:
row, col = i, 0
else:
row, col = rows - 1, (i - rows) + 1
while row >= 0 and col < cols:
cur.append(mat[row][col])
row, col = row - 1, col + 1
if i % 2 != 0:
cur.reverse()
res.extend(cur)
cur.clear()
return res
36 - 2025-08-24 20:51:14 +0300 MSK
Design Circular Queue
Links
Code
class MyCircularQueue:
def __init__(self, k: int):
self._k = k
self._q = [-1] * k
self._i = 0
self._len = 0
def enQueue(self, value: int) -> bool:
if self.isFull():
return False
self._q[self._i] = value
self._i = (self._i + 1) % self._k
self._len += 1
return True
def deQueue(self) -> bool:
if self._len > 0:
self._len -= 1
return True
return False
def Front(self) -> int:
if self.isEmpty():
return -1
return self._q[(self._i - self._len + self._k) % self._k]
def Rear(self) -> int:
if self.isEmpty():
return -1
return self._q[(self._i - 1 + self._k) % self._k]
def isEmpty(self) -> bool:
return self._len == 0
def isFull(self) -> bool:
return self._len == self._k
# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()
37 - 2025-08-24 19:54:22 +0300 MSK
Serialize and Deserialize BST
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string.
"""
if root is None:
return ""
left, right = self.serialize(root.left), self.serialize(root.right)
return f"{root.val}|{len(left)}|{left}{right}"
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree.
"""
if not data:
return None
val, left_len, rest = data.split("|", 2)
root = TreeNode(int(val))
root.left = self.deserialize(rest[:int(left_len)])
root.right = self.deserialize(rest[int(left_len):])
return root
# Your Codec object will be instantiated and called as such:
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# tree = ser.serialize(root)
# ans = deser.deserialize(tree)
# return ans
38 - 2025-08-24 19:38:13 +0300 MSK
Shuffle an Array
Links
Code
class Solution:
def __init__(self, nums: List[int]):
self._orig = nums
self._cur = nums.copy()
def reset(self) -> List[int]:
return self._orig
def shuffle(self) -> List[int]:
return random.sample(self._orig, k=len(self._orig))
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
39 - 2025-08-24 19:30:45 +0300 MSK
Maximum Height of a Triangle
Links
Code
class Solution:
def maxHeightOfTriangle(self, red: int, blue: int) -> int:
return max(self.helper(red, blue), self.helper(blue, red))
def helper(self, red: int, blue: int) -> int:
h = 0
i = 1
while True:
if i % 2 == 1:
if red >= i:
red -= i
else:
break
else:
if blue >= i:
blue -= i
else:
break
h += 1
i += 1
return h
40 - 2025-08-24 19:28:22 +0300 MSK
Count the Number of Incremovable Subarrays I
Links
Code
class Solution:
def incremovableSubarrayCount(self, nums: List[int]) -> int:
result = 0
n = len(nums)
if n == 0:
return 0
prefix_idx, suffix_idx = 0, n - 1
while prefix_idx + 1 < n and nums[prefix_idx + 1] > nums[prefix_idx]:
prefix_idx += 1
if prefix_idx == n - 1:
return (n * (n + 1)) // 2
while suffix_idx > 0 and nums[suffix_idx] > nums[suffix_idx - 1]:
suffix_idx -= 1
result += prefix_idx + 1
result += n - suffix_idx + 1
i = 0
j = suffix_idx
while i <= prefix_idx:
while j < n and nums[i] >= nums[j]:
j += 1
result += n - j
i += 1
return result
41 - 2025-08-24 19:26:17 +0300 MSK
GCD of Odd and Even Sums
Links
Code
class Solution:
def gcdOfOddEvenSums(self, n: int) -> int:
odd_num = 1 + (n - 1) * 2
even_num = 2 + (n - 1) * 2
odd_sum = (n * (1 + odd_num)) // 2
even_sum = (n * (2 + even_num)) // 2
return math.gcd(odd_sum, even_sum)
42 - 2025-08-24 19:18:26 +0300 MSK
Flip Square Submatrix Vertically
Links
Code
class Solution:
def reverseSubmatrix(self, grid: List[List[int]], x: int, y: int, k: int) -> List[List[int]]:
rows, cols = len(grid), len(grid[0])
for col in range(y, y + k):
for row_dlt in range(k // 2):
row1 = x + row_dlt
row2 = (x + k - 1) - row_dlt
grid[row1][col], grid[row2][col] = grid[row2][col], grid[row1][col]
return grid
43 - 2025-08-24 19:07:06 +0300 MSK
Find Books with Polarized Opinions
Links
Code
SELECT r.book_id,
b.title,
b.author,
b.genre,
b.pages,
Max(r.session_rating) - Min(r.session_rating) rating_spread,
Round(( Sum(CASE WHEN r.session_rating < 3 THEN 1 ELSE 0 END + CASE WHEN
r.session_rating >
3 THEN 1 ELSE 0 END) ) / COUNT(r.session_id) ::
Decimal(10, 2), 2) polarization_score
FROM reading_sessions r
INNER JOIN books b USING(book_id)
GROUP BY r.book_id,
b.title,
b.author,
b.genre,
b.pages
HAVING COUNT(r.session_id) > 4
AND Max(r.session_rating) > 3
AND Min(r.session_rating) < 3
AND Round(( Sum(CASE WHEN r.session_rating < 3 THEN 1 ELSE 0 END + CASE
WHEN
r.session_rating >
3 THEN 1 ELSE 0 END) ) / COUNT(r.session_id)
::
Decimal(
10, 2), 2) >= 0.6
ORDER BY polarization_score desc,
b.title desc
44 - 2025-08-24 19:02:12 +0300 MSK
Trionic Array I
Links
Code
class Solution:
def isTrionic(self, nums: List[int]) -> bool:
seg, n = 0, len(nums)
for i in range(1, n):
cur, prv = nums[i], nums[i - 1]
if cur == prv:
return False
if seg == 0:
if cur < prv:
if i == 1:
return False
seg = 1
elif seg == 1:
if cur > prv:
seg = 2
elif seg == 2:
if cur < prv:
return False
return seg == 2
45 - 2025-08-24 18:57:13 +0300 MSK
Earliest Finish Time for Land and Water Rides I
Links
Code
from typing import List
class Solution:
def earliestFinishTime(self,landStartTime: List[int],landDuration: List[int],waterStartTime: List[int],waterDuration: List[int]) -> int:
res = float('inf')
n, m = len(landStartTime), len(waterStartTime)
for i in range(n):
a, d = landStartTime[i], landDuration[i]
for j in range(m):
b, e = waterStartTime[j], waterDuration[j]
land_end = a + d
start_water = max(land_end, b)
finish1 = start_water + e
water_end = b + e
start_land = max(water_end, a)
finish2 = start_land + d
res = min(res, finish1, finish2)
return res
46 - 2025-08-24 18:52:47 +0300 MSK
Check Divisibility by Digit Sum and Product
Links
Code
class Solution:
def checkDivisibility(self, n: int) -> bool:
sm, pr, num = 0, 1, n
while num > 0:
dig = num % 10
num //= 10
sm += dig
pr *= dig
return n % (sm + pr) == 0
47 - 2025-08-24 18:50:32 +0300 MSK
Coupon Code Validator
Links
Code
class Solution:
def validateCoupons(self, code: List[str], businessLine: List[str], isActive: List[bool]) -> List[str]:
res, n = [], len(code)
b_order = {"electronics": 0, "grocery": 1, "pharmacy": 2, "restaurant": 3}
for i in range(n):
if (
isActive[i]
and code[i]
and re.match("^[a-zA-Z0-9_]+$", code[i])
and businessLine[i] in (
"electronics", "grocery", "pharmacy", "restaurant"
)
):
res.append(i)
def sort(i: int) -> tuple[str, str]:
return (b_order[businessLine[i]], code[i])
res.sort(key=sort)
for i in range(len(res)):
res[i] = code[res[i]]
return res
48 - 2025-08-24 18:39:15 +0300 MSK
Hexadecimal and Hexatrigesimal Conversion
Links
Code
class Solution:
def concatHex36(self, n: int) -> str:
res = []
for num, base in ((n ** 3, 36), (n ** 2, 16)):
while num > 0:
dig = num % base
if dig < 10:
res.append(str(dig))
else:
res.append(chr((dig - 10) + 65))
num //= base
res.reverse()
return "".join(res)
49 - 2025-08-24 18:38:15 +0300 MSK
Hexadecimal and Hexatrigesimal Conversion
Links
Code
class Solution:
def concatHex36(self, n: int) -> str:
res, cur = [], []
for num, base in ((n ** 2, 16), (n ** 3, 36)):
while num > 0:
dig = num % base
if dig < 10:
cur.append(str(dig))
else:
cur.append(chr((dig - 10) + 65))
num //= base
cur.reverse()
res.extend(cur)
cur.clear()
return "".join(res)
50 - 2025-08-24 18:22:04 +0300 MSK
Check if Any Element Has Prime Frequency
Links
Code
class Solution:
def checkPrimeFrequency(self, nums: List[int]) -> bool:
def is_prime(v: int) -> bool:
for i in range(2, int(math.sqrt(v)) + 1):
if v % i == 0:
return False
return True
freqs = [0] * 101
for num in nums:
freqs[num] += 1
for freq in freqs:
if freq > 1 and is_prime(freq):
return True
return False
51 - 2025-08-24 18:15:48 +0300 MSK
Generate Tag for Video Caption
Links
Code
class Solution:
def generateTag(self, caption: str) -> str:
res, n, cur = [], len(caption), []
for i in range(n):
ch = caption[i]
if ch.isalpha():
cur.append(ch.lower())
if (ch == " " or i + 1 == n) and cur:
if res:
cur[0] = cur[0].upper()
res.append("".join(cur))
cur.clear()
return "".join(itertools.chain("#", res))[:100]
52 - 2025-08-24 18:07:04 +0300 MSK
Find Books with No Available Copies
Links
Code
SELECT
book_id,
MAX(title) AS title,
MAX(author) AS author,
MAX(genre) AS genre,
MAX(publication_year) AS publication_year,
MAX(total_copies) AS current_borrowers
FROM
(
SELECT
book_id,
title,
author,
genre,publication_year,
total_copies,
total_copies AS total_remain
FROM
library_books
UNION
ALL
SELECT
book_id,
'',
'',
'',
1000,
0,
-1
FROM
borrowing_records
WHERE
return_date IS NULL
) sub
GROUP BY
book_id
HAVING
SUM(total_remain) = 0
ORDER BY
current_borrowers DESC,
title;
53 - 2025-08-24 18:01:04 +0300 MSK
Find Minimum Log Transportation Cost
Links
Code
class Solution:
def minCuttingCost(self, n: int, m: int, k: int) -> int:
ans = 0
if m <= k and n <= k:
return 0
if m > k and n <= k:
ans += (m - k) * k
if n > k and m <= k:
ans += (n - k) * k
return ans
54 - 2025-08-24 17:55:59 +0300 MSK
Smallest Index With Digit Sum Equal to Index
Links
Code
class Solution:
def smallestIndex(self, nums: List[int]) -> int:
for i in range(len(nums)):
num = nums[i]
sm = 0
while num > 0:
sm += num % 10
num //= 10
if sm == i:
return i
return -1
55 - 2025-08-24 17:54:29 +0300 MSK
Minimum Deletions for At Most K Distinct Characters
Links
Code
class Solution:
def minDeletion(self, s: str, k: int) -> int:
freqs, n = [0] * 26, len(s)
for i in range(n):
freqs[ord(s[i]) - 97] += 1
freqs.sort()
res = 0
for i in range(26 - k):
res += freqs[i]
return res
56 - 2025-08-24 17:52:40 +0300 MSK
Minimum Deletions for At Most K Distinct Characters
Links
Code
class Solution:
def minDeletion(self, s: str, k: int) -> int:
freqs, n = [0] * 26, len(s)
for i in range(n):
freqs[ord(s[i]) - 97] += 1
freqs.sort(reverse=True)
res = 0
while len(freqs) > k:
res += freqs.pop()
return res
57 - 2025-08-24 17:46:18 +0300 MSK
Find Most Frequent Vowel and Consonant
Links
Code
class Solution:
def maxFreqSum(self, s: str) -> int:
freqs, n = [0] * 26, len(s)
for i in range(n):
freqs[ord(s[i]) - 97] += 1
max_vow, max_con = 0, 0
vow = tuple(ord(ch) - 97 for ch in ("a", "e", "i", "o", "u"))
for i in range(26):
if i in vow:
max_vow = max(max_vow, freqs[i])
else:
max_con = max(max_con, freqs[i])
return max_vow + max_con
58 - 2025-08-24 17:42:32 +0300 MSK
Maximum Product of Two Digits
Links
Code
class Solution:
def maxProduct(self, n: int) -> int:
num1, num2 = -math.inf, -math.inf
while n > 0:
dig = n % 10
if dig > num2:
num1, num2 = num2, dig
elif dig > num1:
num1 = dig
n //= 10
return num1 * num2
59 - 2025-08-24 17:41:29 +0300 MSK
Maximum Product of Two Digits
Links
Code
class Solution:
def maxProduct(self, n: int) -> int:
dig = []
while n > 0:
heapq.heappush(dig, -(n % 10))
n //= 10
return abs(heapq.heappop(dig) * heapq.heappop(dig))
60 - 2025-08-24 17:40:23 +0300 MSK
Find Closest Person
Links
Code
class Solution:
def findClosest(self, x: int, y: int, z: int) -> int:
diff1, diff2 = abs(z - x), abs(z - y)
if diff1 == diff2:
return 0
if diff1 < diff2:
return 1
return 2
61 - 2025-08-24 17:38:35 +0300 MSK
Minimum Operations to Make Array Sum Divisible by K
Links
Code
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
return sum(nums) % k
62 - 2025-08-24 17:36:34 +0300 MSK
Minimum Pair Removal to Sort Array I
Links
Code
class Solution:
def minimumPairRemoval(self, nums: List[int], ans = 0) -> int:
def notSorted(nums: List[int]) -> bool:
for a, b in pairwise(nums):
if a > b:
return True
return False
while notSorted(nums):
minSum, mnIdx = inf, -1
for i, pair in enumerate(pairwise(nums)):
if sum(pair) < minSum:
minSum, mnIdx, delIdx = sum(pair), i, i + 1
nums[mnIdx] = minSum
del nums[delIdx]
ans += 1
return ans
63 - 2025-08-24 17:22:24 +0300 MSK
Minimum Cost to Reach Every Position
Links
Code
class Solution:
def minCosts(self, cost: List[int]) -> List[int]:
return list(accumulate(cost, min))
64 - 2025-08-24 17:12:42 +0300 MSK
Reverse Degree of a String
Links
Code
class Solution:
def reverseDegree(self, s: str) -> int:
res, n = 0, len(s)
for i in range(n):
res += (i + 1) * (26 - (ord(s[i]) - 97))
return res
65 - 2025-08-24 17:10:49 +0300 MSK
Maximum Containers on a Ship
Links
Code
class Solution:
def maxContainers(self, n: int, w: int, maxWeight: int) -> int:
return min(maxWeight // w, n * n)
66 - 2025-08-24 17:08:09 +0300 MSK
Unique 3-Digit Even Numbers
Links
Code
class Solution:
def totalNumbers(self, digits: List[int]) -> int:
enc = set()
p = [a * 100 + b * 10 + c for a, b, c in itertools.permutations(digits, 3)]
for num in p:
if num not in enc and len(str(num)) == 3:
if num % 2 == 0:
enc.add(num)
return len(enc)
67 - 2025-08-24 17:02:11 +0300 MSK
Find the Largest Almost Missing Integer
Links
Code
class Solution:
def largestInteger(self, nums: List[int], k: int) -> int:
n = len(nums)
subarray_count = defaultdict(int)
for i in range(n - k + 1):
for num in set(nums[i:i+k]):
subarray_count[num] += 1
res = -1
for num, count in subarray_count.items():
if count == 1:
res = max(res, num)
return res
68 - 2025-08-24 16:02:46 +0300 MSK
Transform Array by Parity
Links
Code
class Solution:
def transformArray(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
val = nums[i]
if val % 2 == 0:
nums[i] = 0
else:
nums[i] = 1
nums.sort()
return nums
69 - 2025-08-24 16:00:53 +0300 MSK
Find Products with Valid Serial Numbers
Links
Code
SELECT
*
FROM
Products
WHERE
description ~ '\mSN[0-9]{4}-[0-9]{4}\M'
ORDER BY
product_id ASC;
70 - 2025-08-24 15:55:14 +0300 MSK
Check If Digits Are Equal in String After Operations I
Links
Code
class Solution:
def hasSameDigits(self, s: str) -> bool:
stack = list(map(int, s))
stack.reverse()
while len(stack) > 2:
prev = stack.pop()
for i in reversed(range(len(stack))):
stack[i], prev = (prev + stack[i]) % 10, stack[i]
return stack[0] == stack[1]
71 - 2025-08-24 15:40:47 +0300 MSK
Find Special Substring of Length K
Links
Code
class Solution:
def hasSpecialSubstring(self, s: str, k: int) -> bool:
cnt, n = 0, len(s)
for i in range(n):
if i > 0 and s[i] == s[i - 1]:
cnt += 1
else:
cnt = 1
if cnt != k:
continue
if (
i - cnt >= 0 and s[i - cnt] == s[i]
) or (
i + 1 < n and s[i + 1] == s[i]
):
cnt = 1
else:
return True
return False
72 - 2025-08-24 15:35:22 +0300 MSK
Sum of Good Numbers
Links
Code
class Solution:
def sumOfGoodNumbers(self, nums: List[int], k: int) -> int:
res, n = 0, len(nums)
for i in range(n):
left, right, cur = -1, -1, nums[i]
if i - k >= 0:
left = nums[i - k]
if i + k < n:
right = nums[i + k]
if left < cur > right:
res += cur
return res
73 - 2025-08-24 15:32:58 +0300 MSK
Maximum Difference Between Even and Odd Frequency I
Links
Code
class Solution:
def maxDifference(self, s: str) -> int:
freqs, n = [0] * 26, len(s)
for i in range(n):
freqs[ord(s[i]) - 97] += 1
max_odd, min_even = -math.inf, math.inf
for i in range(26):
freq = freqs[i]
if freq == 0:
continue
if freq % 2 == 0:
min_even = min(min_even, freq)
else:
max_odd = max(max_odd, freq)
return max_odd - min_even
74 - 2025-08-24 15:21:21 +0300 MSK
Find Valid Pair of Adjacent Digits in String
Links
Code
class Solution:
def findValidPair(self, s: str) -> str:
freqs, n = [0] * 10, len(s)
for i in range(n):
freqs[int(s[i])] += 1
for i in range(1, n):
cur, prv = int(s[i]), int(s[i - 1])
if cur != prv and freqs[cur] == cur and freqs[prv] == prv:
return f"{prv}{cur}"
return ""
75 - 2025-08-24 15:17:24 +0300 MSK
Find Valid Emails
Links
Code
SELECT
user_id,
email
FROM
users
WHERE
email ~ '^\w+@[A-Za-z]+\.com$'
ORDER BY
user_id ASC;
76 - 2025-08-24 15:14:50 +0300 MSK
Count Partitions with Even Sum Difference
Links
Code
class Solution:
def countPartitions(self, nums: List[int]) -> int:
sm, n = [0] * len(nums), len(nums)
sm[0] = nums[0]
for i in range(n):
sm[i] = sm[i - 1] + nums[i]
res = 0
for i in range(n - 1):
left = sm[i]
right = sm[-1] - left
res += abs(right - left) % 2 == 0
return res
77 - 2025-08-24 15:11:09 +0300 MSK
Sum of Variable Length Subarrays
Links
Code
class Solution:
def subarraySum(self, nums: List[int]) -> int:
sm, n = [0] * len(nums), len(nums)
sm[0] = nums[0]
for i in range(1, n):
sm[i] = sm[i - 1] + nums[i]
res = 0
for i in range(n):
left = max(0, i - nums[i])
left_sum = 0
if left > 0:
left_sum = sm[left - 1]
res += sm[i] - left_sum
return res
78 - 2025-08-24 15:07:53 +0300 MSK
Maximum Difference Between Adjacent Elements in a Circular Array
Links
Code
class Solution:
def maxAdjacentDistance(self, nums: List[int]) -> int:
res = abs(nums[0] - nums[-1])
for i in range(1, len(nums)):
res = max(res, abs(nums[i] - nums[i - 1]))
return res
79 - 2025-08-24 15:06:30 +0300 MSK
Zigzag Grid Traversal With Skip
Links
Code
class Solution:
def zigzagTraversal(self, grid: List[List[int]]) -> List[int]:
m, n = len(grid), len(grid[0])
res = []
skip = False
for row in range(m):
if row % 2 == 0:
start, end, step = 0, n, 1
else:
start, end, step = n - 1, -1, -1
for col in range(start, end, step):
if not skip:
res.append(grid[row][col])
skip = not skip
return res
80 - 2025-08-24 15:00:31 +0300 MSK
Maximum Subarray With Equal Products
Links
Code
class Solution:
def maxLength(self, A: List[int]) -> int:
N = len(A)
ans = 2
last = {}
i = 0
for j, x in enumerate(A):
for p in prime_divisors(x):
i = max(i, last.get(p, -1) + 1)
last[p] = j
ans = max(ans, j - i + 1)
return ans
def prime_divisors(x):
d = 2
while d * d <= x:
if x % d == 0:
x //= d
while x % d == 0:
x //= d
yield d
d += 1 + d & 1
if x > 1:
yield x
81 - 2025-08-24 14:57:30 +0300 MSK
Substring Matching Pattern
Links
Code
class Solution:
def hasMatch(self, string: str, pattern: str) -> bool:
left_part, right_part = pattern.split("*")
left_idx = string.find(left_part)
right_idx = string.find(right_part, left_idx + len(left_part))
return left_idx != -1 and right_idx != -1
82 - 2025-08-24 14:47:52 +0300 MSK
Minimum Operations to Make Columns Strictly Increasing
Links
Code
class Solution:
def minimumOperations(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
res = 0
for col in range(n):
prv = grid[0][col]
for row in range(1, m):
val = grid[row][col]
if val > prv:
prv = val
else:
diff = (prv + 1) - val
res += diff
prv += 1
return res
83 - 2025-08-24 14:42:38 +0300 MSK
Minimum Number of Operations to Make Elements in Array Distinct
Links
Code
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
freqs, n = [0] * 101, len(nums)
for i in range(n):
freqs[nums[i]] += 1
res = 0
for i in range(0, n, 3):
if max(freqs) == 1:
return res
res += 1
for j in range(i, min(i + 3, n)):
freqs[nums[j]] -= 1
return res
84 - 2025-08-24 14:38:49 +0300 MSK
Count Subarrays of Length Three With a Condition
Links
Code
class Solution:
def countSubarrays(self, nums: List[int]) -> int:
res, n = 0, len(nums)
for i in range(n - 2):
if nums[i] + nums[i + 2] == nums[i + 1] / 2:
res += 1
return res
85 - 2025-08-24 14:36:54 +0300 MSK
Button with Longest Push Time
Links
Code
class Solution:
def buttonWithLongestTime(self, events: List[List[int]]) -> int:
(mx_idx, mx_time), n = events[0], len(events)
for i in range(n):
(cur_idx, cur_time), (prv_idx, prv_time) = events[i], events[i - 1]
diff = cur_time - prv_time
if diff > mx_time or (diff == mx_time and cur_idx < mx_idx):
mx_idx, mx_time = cur_idx, diff
return mx_idx
86 - 2025-08-24 14:33:39 +0300 MSK
Transformed Array
Links
Code
class Solution:
def constructTransformedArray(self, nums: List[int]) -> List[int]:
n = len(nums)
res = [0] * n
for i in range(n):
num = nums[i]
if num == 0:
val = 0
elif num > 0:
val = nums[(i + num) % n]
else:
val = nums[(i - -num + n) % n]
res[i] = val
return res
87 - 2025-08-24 14:28:25 +0300 MSK
Smallest Number With All Set Bits
Links
Code
class Solution:
def smallestNumber(self, n: int) -> int:
res = 0
while n > 0:
res = (res << 1) | 1
n //= 2
return res
88 - 2025-08-24 14:25:47 +0300 MSK
Minimum Positive Sum Subarray
Links
Code
class Solution:
def minimumSumSubarray(self, nums: List[int], l: int, r: int) -> int:
sm, n = [0] * len(nums), len(nums)
cur = 0
for i in range(n):
cur += nums[i]
sm[i] = cur
res = math.inf
for i in range(n):
left = 0
if i > 0:
left = sm[i - 1]
for j in range(i + l - 1, min(i + r, n)):
cur = sm[j] - left
if cur > 0:
res = min(res, cur)
if res == math.inf:
return -1
return res
89 - 2025-08-24 14:09:37 +0300 MSK
Stone Removal Game
Links
Code
class Solution:
def canAliceWin(self, n: int) -> bool:
cnt = 10
while True:
if n >= cnt:
n -= cnt
cnt -= 1
else:
return False
if n >= cnt:
n -= cnt
cnt -= 1
else:
return True
90 - 2025-08-24 14:03:51 +0300 MSK
Make Array Elements Equal to Zero
Links
Code
class Solution:
def countValidSelections(self, nums: List[int]) -> int:
n, res = len(nums), 0
left, right = [0 for _ in range(n)], [0 for _ in range(n)]
for i in range(1, n):
left[i] = left[i - 1] + nums[i - 1]
right[-i - 1] = right[-i] + nums[-i]
for i, num in enumerate(nums):
if num != 0: continue
if left[i] == right[i]: res += 2
if abs(left[i] - right[i]) == 1: res += 1
return res
91 - 2025-08-24 13:57:16 +0300 MSK
Adjacent Increasing Subarrays Detection I
Links
Code
class Solution:
def hasIncreasingSubarrays(self, nums: List[int], k: int) -> bool:
n = len(nums)
cnt = 1
prv_cnt = 0
for i in range(1, n):
cur, prv = nums[i], nums[i - 1]
if cur > prv:
cnt += 1
else:
prv_cnt, cnt = cnt, 1
if cnt >= 2 * k or prv_cnt >= k and cnt >= k:
return True
return False
92 - 2025-08-24 13:46:58 +0300 MSK
Smallest Divisible Digit Product I
Links
Code
class Solution:
def smallestNumber(self, n: int, t: int) -> int:
while True:
cur = n
prd = 1
while cur > 0:
prd *= cur % 10
if prd == 0:
break
cur //= 10
if prd % t == 0:
return n
n += 1
93 - 2025-08-24 13:33:19 +0300 MSK
Check Balanced String
Links
Code
class Solution:
def isBalanced(self, num: str) -> bool:
sm, n = 0, len(num)
for i in range(n):
if i % 2 == 0:
sm += int(num[i])
else:
sm -= int(num[i])
return sm == 0
94 - 2025-08-24 13:31:22 +0300 MSK
Find the Original Typed String I
Links
Code
class Solution:
def possibleStringCount(self, word: str) -> int:
res, n = 1, len(word)
for i in range(1, n):
cur, prev = word[i], word[i - 1]
if cur == prev:
res += 1
return res
95 - 2025-08-24 13:27:05 +0300 MSK
Find X-Sum of All K-Long Subarrays I
Links
Code
class Solution:
def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:
def do_sum (idx: int)-> int:
ctr = Counter(nums[idx:idx + k])
most_freq = nlargest(x, ctr, key = lambda y: (ctr[y], y))
return sum(map(lambda y: y * ctr[y], most_freq))
return tuple(map(do_sum,range(len(nums)+1 - k)))
96 - 2025-08-24 13:21:47 +0300 MSK
Construct the Minimum Bitwise Array I
Links
Code
class Solution:
def minBitwiseArray(self, nums: List[int]) -> List[int]:
ans = []
for i in nums:
for j in range(i):
if j | (j + 1) == i:
ans.append(j)
break
else:
ans.append(-1)
return ans
97 - 2025-08-24 13:10:51 +0300 MSK
Find the K-th Character in String Game I
Links
Code
class Solution:
def kthCharacter(self, k: int) -> str:
res = 0
while k != 1:
ln = k.bit_length() - 1
if (1 << ln) == k:
ln -= 1
k -= 1 << ln
res += 1
return chr(res + 97)
98 - 2025-08-24 13:05:10 +0300 MSK
Minimum Element After Replacement With Digit Sum
Links
Code
class Solution:
def minElement(self, nums: List[int]) -> int:
res = math.inf
for num in nums:
cur = 0
while num > 0:
cur += num % 10
num //= 10
res = min(res, cur)
return res
99 - 2025-08-24 12:59:57 +0300 MSK
The Two Sneaky Numbers of Digitville
Links
Code
class Solution:
def getSneakyNumbers(self, nums: List[int]) -> List[int]:
n = len(nums) - 2
xor_all = 0
for num in nums:
xor_all ^= num
for num in range(n):
xor_all ^= num
rightmost_bit = xor_all & -xor_all
dup1, dup2 = 0, 0
for num in nums:
if num & rightmost_bit:
dup1 ^= num
else:
dup2 ^= num
for num in range(n):
if num & rightmost_bit:
dup1 ^= num
else:
dup2 ^= num
return [dup1, dup2]
100 - 2025-08-24 12:47:23 +0300 MSK
Find Indices of Stable Mountains
Links
Code
class Solution:
def stableMountains(self, height: List[int], threshold: int) -> List[int]:
res, n = [], len(height)
for i in range(1, n):
cur, prv = height[i], height[i - 1]
if prv > threshold:
res.append(i)
return res
101 - 2025-08-24 12:44:46 +0300 MSK
Convert Date to Binary
Links
Code
class Solution:
def convertDateToBinary(self, date: str) -> str:
res, cur = [], []
for num in map(int, (date[:4], date[5:7], date[-2:])):
while num > 0:
cur.append(num & 1)
num >>= 1
cur.reverse()
res.append("".join(map(str, cur)))
cur.clear()
return "-".join(res)
102 - 2025-08-24 12:44:03 +0300 MSK
Convert Date to Binary
Links
Code
class Solution:
def convertDateToBinary(self, date: str) -> str:
res, cur = [], []
for num in map(int, (date[:4], date[5:7], date[-2:])):
while num > 0:
cur.append(num % 2)
num //= 2
cur.reverse()
res.append("".join(map(str, cur)))
cur.clear()
return "-".join(res)
103 - 2025-08-24 12:38:10 +0300 MSK
Check if Two Chessboard Squares Have the Same Color
Links
Code
class Solution:
def checkTwoChessboards(self, coordinate1: str, coordinate2: str) -> bool:
row1, col1 = ord(coordinate1[0]) - 97, int(coordinate1[1]) - 1
row2, col2 = ord(coordinate2[0]) - 97, int(coordinate2[1]) - 1
if row1 % 2 == 0:
is_black1 = col1 % 2 == 0
else:
is_black1 = col1 % 2 != 0
if row2 % 2 == 0:
is_black2 = col2 % 2 == 0
else:
is_black2 = col2 % 2 != 0
return is_black1 == is_black2
104 - 2025-08-24 12:34:32 +0300 MSK
Find the Key of the Numbers
Links
Code
class Solution:
def generateKey(self, num1: int, num2: int, num3: int) -> int:
res = 0
cnt = 0
while num1 > 0 and num2 > 0 and num3 > 0:
res += min(num1 % 10, num2 % 10, num3 % 10) * (10 ** cnt)
cnt += 1
num1 //= 10
num2 //= 10
num3 //= 10
return res
105 - 2025-08-24 12:31:27 +0300 MSK
Final Array State After K Multiplication Operations I
Links
Code
class Solution:
def getFinalState(self, nums: List[int], k: int, multiplier: int):
hp = [(val, i) for i, val in enumerate(nums)]
heapq.heapify(hp)
for _ in range(k):
_, i = heapq.heappop(hp)
nums[i] *= multiplier
heapq.heappush(hp, (nums[i], i))
return nums
106 - 2025-08-24 12:29:48 +0300 MSK
Final Array State After K Multiplication Operations I
Links
Code
class Solution:
def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:
pos, n = defaultdict(list), len(nums)
hp = nums.copy()
heapq.heapify(hp)
for i in reversed(range(n)):
heapq.heappush(pos[nums[i]], i)
while k > 0:
k -= 1
val = heapq.heappop(hp)
new_val = val * multiplier
heapq.heappush(hp, new_val)
idx = heapq.heappop(pos[val])
nums[idx] = new_val
heapq.heappush(pos[new_val], idx)
return nums
107 - 2025-08-24 12:20:45 +0300 MSK
Count Substrings That Satisfy K-Constraint I
Links
Code
class Solution:
def countKConstraintSubstrings(self, s: str, k: int) -> int:
res, n, ones, l = 0, len(s), 0, 0
for r in range(n):
ones += int(s[r])
while (ones > k) and ((r - l + 1) - ones) > k:
ones -= int(s[l])
l += 1
res += r - l + 1
return res
108 - 2025-08-24 11:46:23 +0300 MSK
Snake in Matrix
Links
Code
class Solution:
def finalPositionOfSnake(self, n: int, commands: List[str]) -> int:
col, row = 0, 0
for cmd in commands:
if cmd == "RIGHT":
col += 1
elif cmd == "UP":
row -= 1
elif cmd == "DOWN":
row += 1
else:
col -= 1
return row * n + col
109 - 2025-08-24 11:43:54 +0300 MSK
Find the Number of Winning Players
Links
Code
class Solution:
def winningPlayerCount(self, n: int, pick: List[List[int]]) -> int:
res, n, freqs = 0, len(pick), [[0] * 11 for _ in range(11)]
for i in range(n):
pl, cl = pick[i]
freqs[pl][cl] += 1
for i in range(len(freqs)):
if max(freqs[i]) > i:
res += 1
return res
110 - 2025-08-24 10:55:08 +0300 MSK
Longest Subarray of 1’s After Deleting One Element
Links
Code
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
res, n, cnt1, cnt2 = 0, len(nums), 0, 0
for i in range(len(nums)):
cur = nums[i]
if cur == 1:
cnt2 += 1
res = max(res, cnt1 + cnt2)
elif cur == 0:
cnt1, cnt2 = cnt2, 0
if res == n:
return res - 1
return res
111 - 2025-08-23 20:17:19 +0300 MSK
Find if Digit Game Can Be Won
Links
Code
class Solution:
def canAliceWin(self, nums: List[int]) -> bool:
sm_single, sm_double, sm_all = 0, 0, 0
for num in nums:
if num < 10:
sm_single += num
elif num < 100:
sm_double += num
sm_all += num
return sm_single > (sm_all - sm_single) or sm_double > (sm_all - sm_double)
112 - 2025-08-23 19:28:34 +0300 MSK
Number of Bit Changes to Make Two Integers Equal
Links
Code
class Solution:
def minChanges(self, n: int, k: int) -> int:
res = 0
if n < k:
return -1
while k > 0 or n > 0:
n1, k1 = n & 1, k & 1
if n1 != k1 and n1 == 0 and k1 == 1:
return -1
if n1 != k1:
res += 1
n >>= 1
k >>= 1
return res
113 - 2025-08-23 18:30:08 +0300 MSK
Find the Minimum Area to Cover All Ones II
Links
Code
class Solution:
def minimumSum2(
self, grid: List[List[int]], u: int, d: int, l: int, r: int
) -> int:
min_i = len(grid)
max_i = 0
min_j = len(grid[0])
max_j = 0
for i in range(u, d + 1):
for j in range(l, r + 1):
if grid[i][j] == 1:
min_i = min(min_i, i)
min_j = min(min_j, j)
max_i = max(max_i, i)
max_j = max(max_j, j)
return (
(max_i - min_i + 1) * (max_j - min_j + 1)
if min_i <= max_i
else sys.maxsize // 3
)
def rotate(self, vec: List[List[int]]) -> List[List[int]]:
n = len(vec)
m = len(vec[0]) if n > 0 else 0
ret = [[0] * n for _ in range(m)]
for i in range(n):
for j in range(m):
ret[m - j - 1][i] = vec[i][j]
return ret
def solve(self, grid: List[List[int]]) -> int:
n = len(grid)
m = len(grid[0]) if n > 0 else 0
res = n * m
for i in range(n - 1):
for j in range(m - 1):
res = min(
res,
self.minimumSum2(grid, 0, i, 0, m - 1)
+ self.minimumSum2(grid, i + 1, n - 1, 0, j)
+ self.minimumSum2(grid, i + 1, n - 1, j + 1, m - 1),
)
res = min(
res,
self.minimumSum2(grid, 0, i, 0, j)
+ self.minimumSum2(grid, 0, i, j + 1, m - 1)
+ self.minimumSum2(grid, i + 1, n - 1, 0, m - 1),
)
for i in range(n - 2):
for j in range(i + 1, n - 1):
res = min(
res,
self.minimumSum2(grid, 0, i, 0, m - 1)
+ self.minimumSum2(grid, i + 1, j, 0, m - 1)
+ self.minimumSum2(grid, j + 1, n - 1, 0, m - 1),
)
return res
def minimumSum(self, grid: List[List[int]]) -> int:
rgrid = self.rotate(grid)
return min(self.solve(grid), self.solve(rgrid))
114 - 2025-08-22 21:36:17 +0300 MSK
Find the Winning Player in Coin Game
Links
Code
class Solution:
def winningPlayer(self, x: int, y: int) -> str:
y //= 4
x = min(x, y)
if x % 2 == 1:
return "Alice"
else:
return "Bob"
115 - 2025-08-22 21:29:25 +0300 MSK
Lexicographically Smallest String After a Swap
Links
Code
class Solution:
def getSmallestString(self, s: str) -> str:
res = list(s)
for i in range(len(s) - 1):
cur, nxt = int(s[i]), int(s[i + 1])
if cur % 2 == nxt % 2 and cur > nxt:
res[i], res[i + 1] = s[i + 1], s[i]
break
return "".join(res)
116 - 2025-08-22 21:16:52 +0300 MSK
Find the Encrypted String
Links
Code
class Solution:
def getEncryptedString(self, s: str, k: int) -> str:
res = []
for i in range(len(s)):
res.append(s[(i + k) % len(s)])
return "".join(res)
117 - 2025-08-22 21:13:56 +0300 MSK
Alternating Groups I
Links
Code
class Solution:
def numberOfAlternatingGroups(self, colors: List[int]) -> int:
res = 0
if colors[0] != colors[-1] and colors[0] != colors[1]:
res += 1
if colors[-1] != colors[-2] and colors[-1] != colors[0]:
res += 1
for i in range(1, len(colors) - 1):
if colors[i] != colors[i - 1] and colors[i] != colors[i + 1]:
res += 1
return res
118 - 2025-08-22 21:08:45 +0300 MSK
Minimum Average of Smallest and Largest Elements
Links
Code
class Solution:
def minimumAverage(self, nums: List[int]) -> float:
av = []
nums.sort()
for i in range(len(nums) // 2):
heapq.heappush(av, nums[i] + nums[len(nums) - i - 1])
return heapq.heappop(av) / 2
119 - 2025-08-22 21:06:36 +0300 MSK
Find Minimum Operations to Make All Elements Divisible by Three
Links
Code
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
res = 0
for i in range(len(nums)):
res += nums[i] % 3 != 0
return res
120 - 2025-08-22 21:05:07 +0300 MSK
Find Minimum Operations to Make All Elements Divisible by Three
Links
Code
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
res = 0
for i in range(len(nums)):
res += min(nums[i] % 3, ((nums[i] // 3) + 1) * 3 - nums[i])
return res
121 - 2025-08-22 21:02:15 +0300 MSK
Count Pairs That Form a Complete Day I
Links
Code
class Solution:
def countCompleteDayPairs(self, hours: List[int]) -> int:
freqs = [0] * 24
for i in range(len(hours)):
freqs[hours[i] % 24] += 1
res = 0
for i in range(len(hours)):
hr = hours[i] % 24
freqs[hr] -= 1
if hr == 0:
res += freqs[hr]
else:
res += freqs[24 - hr]
return res
122 - 2025-08-22 20:53:33 +0300 MSK
Find the Child Who Has the Ball After K Seconds
Links
Code
class Solution:
def numberOfChild(self, n: int, k: int) -> int:
circleback = (n - 1) * 2
k %= circleback
if k < n:
return k
return circleback - k
123 - 2025-08-22 20:44:21 +0300 MSK
Clear Digits
Links
Code
class Solution:
def clearDigits(self, s: str) -> str:
res = []
for i in range(len(s)):
ch = s[i]
if not ch.isdigit():
res.append(ch)
elif res:
res.pop()
return "".join(res)
124 - 2025-08-22 20:41:37 +0300 MSK
Minimum Number of Chairs in a Waiting Room
Links
Code
class Solution:
def minimumChairs(self, s: str) -> int:
left = 0
res = 0
for i in range(len(s)):
if s[i] == "E":
if left > 0:
left -= 1
else:
res += 1
else:
left += 1
return res
125 - 2025-08-22 20:34:34 +0300 MSK
Find the Number of Good Pairs I
Links
Code
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
freqs = [0] * 51
for i in range(len(nums2)):
freqs[nums2[i]] += 1
res = 0
for i in range(len(nums1)):
for num2 in range(1, len(freqs)):
if nums1[i] % (num2 * k) == 0:
res += freqs[num2]
return res
126 - 2025-08-22 20:29:48 +0300 MSK
Find the XOR of Numbers Which Appear Twice
Links
Code
class Solution:
def duplicateNumbersXOR(self, nums: List[int]) -> int:
freqs = [0] * 51
res = 0
for i in range(len(nums)):
freqs[nums[i]] += 1
if freqs[nums[i]] == 2:
res ^= nums[i]
return res
127 - 2025-08-22 20:27:37 +0300 MSK
Special Array I
Links
Code
class Solution:
def isArraySpecial(self, nums: List[int]) -> bool:
for i in range(1, len(nums)):
cur, prev = nums[i] % 2 == 0, nums[i - 1] % 2 == 0
if cur == prev:
return False
return True
128 - 2025-08-22 20:25:28 +0300 MSK
Permutation Difference between Two Strings
Links
Code
class Solution:
def findPermutationDifference(self, s: str, t: str) -> int:
pos = [0] * 26
for i in range(len(s)):
pos[ord(s[i]) - 97] += i
res = 0
for i in range(len(t)):
res += abs(i - pos[ord(t[i]) - 97])
return res
129 - 2025-08-22 20:22:48 +0300 MSK
Check if Grid Satisfies Conditions
Links
Code
class Solution:
def satisfiesConditions(self, grid: List[List[int]]) -> bool:
rows, cols = len(grid), len(grid[0])
for row in range(rows):
for col in range(cols):
val = grid[row][col]
if row + 1 < rows and val != grid[row + 1][col]:
return False
if col + 1 < cols and val == grid[row][col + 1]:
return False
return True
130 - 2025-08-22 20:20:58 +0300 MSK
Valid Word
Links
Code
class Solution:
def isValid(self, word: str) -> bool:
vws = ('a', 'e', 'i', 'o', 'u')
if len(word) < 3:
return False
has_vw, has_cons = False, False
for i in range(len(word)):
ch = word[i]
if ch.isalpha():
if ch.lower() in vws:
has_vw = True
else:
has_cons = True
elif not ch.isdigit():
return False
return has_vw and has_cons
131 - 2025-08-22 20:15:56 +0300 MSK
Find the Integer Added to Array I
Links
Code
class Solution:
def addedInteger(self, nums1: List[int], nums2: List[int]) -> int:
nums1.sort()
nums2.sort()
return nums2[0] - nums1[0]
132 - 2025-08-22 20:12:59 +0300 MSK
Make a Square with the Same Color
Links
Code
class Solution:
def canMakeSquare(self, grid: List[List[str]]) -> bool:
rows, cols = len(grid), len(grid[0])
moves = ((0, 0), (0, -1), (-1, -1), (-1, 0))
for row in range(1, rows):
for col in range(1, cols):
cnt = 0
for row_dlt, col_dlt in moves:
if grid[row + row_dlt][col + col_dlt] == "W":
cnt += 1
else:
cnt -= 1
if cnt in (2, -2, 4, -4):
return True
return False
133 - 2025-08-22 20:03:50 +0300 MSK
Count the Number of Special Characters I
Links
Code
class Solution:
def numberOfSpecialChars(self, word: str) -> int:
freqs = [0] * 26
res = 0
for i in range(len(word)):
char = word[i]
idx = ord(char)
if char.isupper():
idx -= 65
freqs[idx] |= 0x01
else:
idx -= 97
freqs[idx] |= 0x10
for i in range(len(freqs)):
freq = freqs[i]
if freq ^ 0x11 == 0:
res += 1
return res
134 - 2025-08-22 19:58:17 +0300 MSK
Latest Time You Can Obtain After Replacing Characters
Links
Code
class Solution:
def findLatestTime(self, time_str):
len_time_str = len(time_str)
ret_val = ''
i = 0
while (i < len_time_str):
c = time_str[i]
if (c == '?'):
if (i == 0):
if (time_str[i+1] == '?'):
ret_val += '1'
elif (time_str[i+1] in ('0', '1')):
ret_val += '1'
else:
ret_val += '0'
elif (i == 1):
if (time_str[i-1] == '?'):
ret_val += '1'
elif (time_str[i-1] in ('0')):
ret_val += '9'
elif (time_str[i-1] in ('1')):
ret_val += '1'
else:
ret_val += '0'
elif (i == 3):
ret_val += '5'
elif (i == 4):
ret_val += '9'
else:
ret_val += c
i += 1
return ret_val
135 - 2025-08-22 19:49:07 +0300 MSK
Longest Strictly Increasing or Strictly Decreasing Subarray
Links
Code
class Solution:
def longestMonotonicSubarray(self, nums: List[int]) -> int:
inc_len, dec_len, cur_len, cur_state = 1, 1, 1, 0
for i in range(1, len(nums)):
cur, prev = nums[i], nums[i - 1]
if cur > prev:
if cur_state == 1:
cur_len += 1
else:
cur_state = 1
cur_len = 2
inc_len = max(inc_len, cur_len)
elif cur == prev:
cur_len = 1
cur_state = 0
else:
if cur_state == -1:
cur_len += 1
else:
cur_state = -1
cur_len = 2
dec_len = max(dec_len, cur_len)
return max(inc_len, dec_len)
136 - 2025-08-22 19:43:35 +0300 MSK
Harshad Number
Links
Code
class Solution:
def sumOfTheDigitsOfHarshadNumber(self, x: int) -> int:
cur = x
sm = 0
while cur > 0:
sm += cur % 10
cur //= 10
if x % sm == 0:
return sm
return -1
137 - 2025-08-22 19:42:24 +0300 MSK
Shortest Subarray With OR at Least K I
Links
Code
class Solution:
def minimumSubarrayLength(self, nums: List[int], k: int) -> int:
n = len(nums)
min_len = math.inf
for i in range(n):
curr = 0
for j in range(i, n):
curr |= nums[j]
if curr >= k:
min_len = min(min_len , j - i + 1)
break
if min_len == math.inf:
return -1
return min_len
138 - 2025-08-22 19:24:16 +0300 MSK
Maximum Length Substring With Two Occurrences
Links
Code
class Solution:
def maximumLengthSubstring(self, s: str) -> int:
ans = ii = 0
freq = Counter()
for i, ch in enumerate(s):
freq[ch] += 1
while freq[ch] == 3:
freq[s[ii]] -= 1
ii += 1
ans = max(ans, i - ii + 1)
return ans
139 - 2025-08-22 19:19:46 +0300 MSK
Existence of a Substring in a String and Its Reverse
Links
Code
class Solution:
def isSubstringPresent(self, s: str) -> bool:
for i in range(1, len(s)):
cur, prev = s[i], s[i - 1]
for j in range(i, len(s)):
cur2, prev2 = s[j], s[j - 1]
if cur == prev2 and prev == cur2:
return True
return False
140 - 2025-08-22 19:14:44 +0300 MSK
Find the Sum of Encrypted Integers
Links
Code
class Solution:
def sumOfEncryptedInt(self, nums: List[int]) -> int:
res = 0
for i in range(len(nums)):
cur = nums[i]
max_dig = 0
enc = 0
cnt = 0
while cur > 0:
max_dig = max(max_dig, cur % 10)
cur //= 10
enc += 10 ** cnt
cnt += 1
enc *= max_dig
res += enc
return res
141 - 2025-08-22 19:10:19 +0300 MSK
Apple Redistribution into Boxes
Links
Code
class Solution:
def minimumBoxes(self, apple: List[int], capacity: List[int]) -> int:
apples = sum(apple)
capacity.sort(reverse=True)
for i in range(len(capacity)):
apples = max(apples - capacity[i], 0)
if apples == 0:
return i + 1
raise Exception
142 - 2025-08-22 19:03:00 +0300 MSK
Distribute Elements Into Two Arrays I
Links
Code
class Solution:
def resultArray(self, nums):
len_nums = len(nums)
arr1 = [nums[0]]
arr2 = [nums[1]]
for i in range(2, len(nums)):
if arr1[-1] > arr2[-1]:
arr1.append(nums[i])
else:
arr2.append(nums[i])
arr1.extend(arr2)
return arr1
143 - 2025-08-22 18:58:03 +0300 MSK
Minimum Operations to Exceed Threshold Value I
Links
Code
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
nums.sort()
for i in range(len(nums)):
if nums[i] >= k:
return i
return len(nums)
144 - 2025-08-22 18:56:27 +0300 MSK
Split the Array
Links
Code
class Solution:
def isPossibleToSplit(self, nums: List[int]) -> bool:
freqs = [0] * 101
for num in nums:
freqs[num] += 1
if freqs[num] == 3:
return False
return True
145 - 2025-08-22 18:53:34 +0300 MSK
Count Prefix and Suffix Pairs I
Links
Code
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
res = 0
for i in range(len(words)):
w1 = words[i]
for j in range(i + 1, len(words)):
w2 = words[j]
if w2.startswith(w1) and w2.endswith(w1):
res += 1
return res
146 - 2025-08-22 18:48:54 +0300 MSK
Maximum Number of Operations With the Same Score I
Links
Code
class Solution:
def maxOperations(self, nums: List[int]) -> int:
target = sum(nums[:2])
res = 1
for i in range(2, len(nums) - 1, 2):
if sum(nums[i:i + 2]) == target:
res += 1
else:
break
return res
147 - 2025-08-22 18:46:45 +0300 MSK
Modify the Matrix
Links
Code
class Solution:
def modifiedMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
rows, cols = len(matrix), len(matrix[0])
for col in range(cols):
max_val = -1
for row in range(rows):
max_val = max(max_val, matrix[row][col])
for row in range(rows):
if matrix[row][col] == -1:
matrix[row][col] = max_val
return matrix
148 - 2025-08-22 18:44:22 +0300 MSK
Ant on the Boundary
Links
Code
class Solution:
def returnToBoundaryCount(self, nums: List[int]) -> int:
res = 0
pos = nums[0]
for num in nums[1:]:
pos += num
if pos == 0:
res += 1
return res
149 - 2025-08-22 18:43:10 +0300 MSK
Type of Triangle
Links
Code
class Solution:
def triangleType(self, nums: List[int]) -> str:
s1, s2, s3 = nums
if s1 == s2 == s3:
return "equilateral"
if s1 + s2 <= s3 or s1 + s3 <= s2 or s2 + s3 <= s1:
return "none"
if s1 == s2 or s2 == s3 or s1 == s3:
return "isosceles"
if s1 != s2 and s2 != s3 and s1 != s3:
return "scalene"
return "none"
150 - 2025-08-22 18:39:40 +0300 MSK
Number of Changing Keys
Links
Code
class Solution:
def countKeyChanges(self, s: str) -> int:
res = 0
for i in range(1, len(s)):
cur, prev = ord(s[i]), ord(s[i - 1])
if cur < 97:
cur += 32
if prev < 97:
prev += 32
if cur != prev:
res += 1
return res
151 - 2025-08-22 18:38:14 +0300 MSK
Number of Changing Keys
Links
Code
class Solution:
def countKeyChanges(self, s: str) -> int:
res = 0
for i in range(1, len(s)):
cur, prev = s[i].lower(), s[i - 1].lower()
if cur != prev:
res += 1
return res
152 - 2025-08-22 18:36:52 +0300 MSK
Minimum Number of Pushes to Type Word I
Links
Code
class Solution:
def minimumPushes(self, word: str) -> int:
freqs = [0] * 26
for char in word:
freqs[ord(char) - 97] += 1
freqs.sort()
res = 0
for i in range(26):
freq = freqs[26 - i - 1]
if freq == 0:
break
res += freq * (i // 8 + 1)
return res
153 - 2025-08-22 18:30:44 +0300 MSK
Minimum Number of Pushes to Type Word I
Links
Code
class Solution:
def minimumPushes(self, word: str) -> int:
freqs = [0] * 26
for char in word:
freqs[ord(char) - 97] += 1
freqs.sort()
cost = 1
res = 0
while freqs and freqs[-1] != 0:
for _ in range(8):
if not freqs:
break
freq = freqs.pop()
if freq == 0:
break
res += freq * cost
cost += 1
return res
154 - 2025-08-22 18:25:20 +0300 MSK
Divide an Array Into Subarrays With Minimum Cost I
Links
Code
class Solution:
def minimumCost(self, nums: List[int]) -> int:
nums.reverse()
first = nums.pop()
nums.sort()
return first + sum(nums[:2])
155 - 2025-08-22 18:22:55 +0300 MSK
Maximum Area of Longest Diagonal Rectangle
Links
Code
class Solution:
def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int:
max_diag, max_area = 0, 0
for length, width in dimensions:
diag = length ** 2 + width ** 2
area = length * width
if diag > max_diag or (diag == max_diag and area > max_area):
max_diag, max_area = diag, area
return max_area
156 - 2025-08-22 18:19:44 +0300 MSK
Smallest Missing Integer Greater Than Sequential Prefix Sum
Links
Code
class Solution:
def missingInteger(self, nums: List[int]) -> int:
s = set(nums)
x = nums[0] - 1
seqSum = 0
for i in nums:
if i - x == 1:
seqSum += i
x = i
else:
break
index = seqSum
while True:
if index not in s:
return index
index += 1
157 - 2025-08-22 17:02:28 +0300 MSK
Check if Bitwise OR Has Trailing Zeros
Links
Code
class Solution:
def hasTrailingZeros(self, nums: List[int]) -> bool:
cnt = 0
for num in nums:
if num & 1 == 0:
cnt += 1
if cnt == 2:
return True
return False
158 - 2025-08-22 16:56:33 +0300 MSK
Minimum Number Game
Links
Code
class Solution:
def numberGame(self, nums: List[int]) -> List[int]:
res = []
nums.sort(reverse=True)
while nums:
al, bob = nums.pop(), nums.pop()
res.extend((bob, al))
return res
159 - 2025-08-22 14:49:18 +0300 MSK
Find Missing and Repeated Values
Links
Code
class Solution:
def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
n = len(grid)
freqs = [0] * (n ** 2 + 1)
res1 = None
for row in grid:
for num in row:
freqs[num] += 1
if freqs[num] == 2:
res1 = num
return res1, freqs[1:].index(0) + 1
160 - 2025-08-22 14:41:39 +0300 MSK
Count Tested Devices After Test Operations
Links
Code
class Solution:
def countTestedDevices(self, batteryPercentages: List[int]) -> int:
res = 0
for i, perc in enumerate(batteryPercentages):
if perc - res > 0:
res += 1
return res
161 - 2025-08-22 14:33:33 +0300 MSK
Find Common Elements Between Two Arrays
Links
Code
class Solution:
def findIntersectionValues(self, nums1: List[int], nums2: List[int]) -> List[int]:
freqs1, freqs2 = [0] * 101, [0] * 101
for num in nums1:
freqs1[num] += 1
for num in nums2:
freqs2[num] += 1
res1, res2 = 0, 0
for num, freq in enumerate(freqs1):
if freqs2[num] > 0:
res1 += freq
for num, freq in enumerate(freqs2):
if freqs1[num] > 0:
res2 += freq
return res1, res2
162 - 2025-08-22 14:30:04 +0300 MSK
Find the Peaks
Links
Code
class Solution:
def findPeaks(self, mountain: List[int]) -> List[int]:
res = []
for i in range(1, len(mountain) - 1):
if mountain[i - 1] < mountain[i] > mountain[i + 1]:
res.append(i)
return res
163 - 2025-08-22 14:28:05 +0300 MSK
Matrix Similarity After Cyclic Shifts
Links
Code
class Solution:
def areSimilar(self, mat: List[List[int]], k: int) -> bool:
cols = len(mat[0])
for row in range(len(mat)):
is_even = row % 2 == 0
for col in range(cols):
if is_even:
new_col = (col - k + cols) % cols
else:
new_col = (col + k) % cols
if mat[row][col] != mat[row][new_col]:
return False
return True
164 - 2025-08-22 14:23:13 +0300 MSK
Find Words Containing Character
Links
Code
class Solution:
def findWordsContaining(self, words: List[str], x: str) -> List[int]:
for i in range(len(words)):
if x in words[i]:
words[i] = i
else:
words[i] = -1
words.sort(reverse=True)
while words and words[-1] == -1:
words.pop()
return words
165 - 2025-08-22 14:20:44 +0300 MSK
Find Words Containing Character
Links
Code
class Solution:
def findWordsContaining(self, words: List[str], x: str) -> List[int]:
res = []
for i, word in enumerate(words):
if x in word:
res.append(i)
return res
166 - 2025-08-22 14:19:56 +0300 MSK
Make Three Strings Equal
Links
Code
class Solution:
def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int:
n1, n2, n3 = len(s1), len(s2), len(s3)
for i in range(max(n1, n2, n3)):
fail = True
if i < n1 and i < n2 and i < n3:
c1, c2, c3 = s1[i], s2[i], s3[i]
if c1 == c2 and c2 == c3:
fail = False
if not fail:
continue
if i == 0:
return -1
return max(n1 - i, 0) + max(n2 - i, 0) + max(n3 - i, 0)
return 0
167 - 2025-08-22 14:06:34 +0300 MSK
Maximum Strong Pair XOR I
Links
Code
class Solution:
def maximumStrongPairXor(self, nums: List[int]) -> int:
nums.sort()
n, l, r, res = len(nums), 0, 0, 0
while r < n:
num1, num2 = nums[l], nums[r]
if num2 - num1 > num1:
l += 1
continue
for i in range(l, r):
res = max(res, nums[i] ^ num2)
r += 1
return res
168 - 2025-08-22 13:59:13 +0300 MSK
Maximum Strong Pair XOR I
Links
Code
class Solution:
def maximumStrongPairXor(self, nums: List[int]) -> int:
max_xor = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
num1, num2 = nums[i], nums[j]
if abs(num2 - num1) <= min(num1, num2):
max_xor = max(max_xor, num1 ^ num2)
return max_xor
169 - 2025-08-22 13:58:21 +0300 MSK
Maximum Strong Pair XOR I
Links
Code
class Solution:
def maximumStrongPairXor(self, nums: List[int]) -> int:
max_xor = 0
for num1, num2 in itertools.permutations(nums, 2):
if abs(num2 - num1) <= min(num1, num2):
max_xor = max(max_xor, num1 ^ num2)
return max_xor
170 - 2025-08-22 13:53:08 +0300 MSK
Distribute Candies Among Children I
Links
Code
class Solution:
def distributeCandies(self, n: int, limit: int) -> int:
min_first = max(0, n - 2 * limit)
max_first = min(n, limit)
ways = 0
for i in range(min_first, max_first + 1):
N = n - i
min_ch2 = max(0, N - limit)
max_ch2 = min(N, limit)
ways += max_ch2 - min_ch2 + 1
return ways
171 - 2025-08-22 13:44:20 +0300 MSK
Find Champion I
Links
Code
class Solution:
def findChampion(self, grid: List[List[int]]) -> int:
loses = [False] * len(grid)
for row in range(len(grid)):
for col in range(len(grid)):
if row == col:
continue
val = grid[row][col]
if val == 1:
loses[col] = True
else:
loses[row] = True
return loses.index(False)
172 - 2025-08-22 13:37:11 +0300 MSK
Find the K-or of an Array
Links
Code
class Solution:
def findKOr(self, nums: List[int], k: int) -> int:
freqs = [0] * 31
for num in nums:
i = 0
while num > 0:
if num & 1 == 1:
freqs[i] += 1
i += 1
num >>= 1
res = 0
for i, freq in enumerate(freqs):
if freq >= k:
res |= 1 << i
return res
173 - 2025-08-22 09:54:03 +0300 MSK
Find the Minimum Area to Cover All Ones I
Links
Code
class Solution:
def minimumArea(self, grid: List[List[int]]) -> int:
min_row, max_row = math.inf, -math.inf
min_col, max_col = math.inf, -math.inf
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == 0:
continue
min_row, max_row = min(min_row, row), max(max_row, row)
min_col, max_col = min(min_col, col), max(max_col, col)
return (max_row - min_row + 1) * (max_col - min_col + 1)
174 - 2025-08-21 19:04:22 +0300 MSK
Subarrays Distinct Element Sum of Squares I
Links
Code
class Solution:
def sumCounts(self, nums: List[int]) -> int:
n = len(nums)
result = 0
for i in range(n):
s = set()
for j in range(i, n):
s.add(nums[j])
result += len(s) ** 2
return result
175 - 2025-08-21 19:01:40 +0300 MSK
Method Chaining
Links
Code
import pandas as pd
def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
return animals[animals['weight'] > 100].sort_values(by='weight', ascending=False)[['name']]
176 - 2025-08-21 18:59:14 +0300 MSK
Reshape Data: Melt
Links
Code
import pandas as pd
def meltTable(report: pd.DataFrame) -> pd.DataFrame:
report = report.melt(
id_vars=["product"],
value_vars=["quarter_1", "quarter_2", "quarter_3", "quarter_4"],
var_name="quarter",
value_name="sales",
)
return report
177 - 2025-08-21 18:58:06 +0300 MSK
Reshape Data: Pivot
Links
Code
import pandas as pd
def pivotTable(weather: pd.DataFrame) -> pd.DataFrame:
ans = weather.pivot(index='month', columns='city', values='temperature')
return ans
178 - 2025-08-21 18:57:41 +0300 MSK
Minimum Sum of Mountain Triplets I
Links
Code
class Solution:
def minimumSum(self, nums: List[int]) -> int:
n = len(nums)
min_left, min_right = [0] * n, [0] * n
cur_min = math.inf
for i in range(n):
cur_min = min(cur_min, nums[i])
min_left[i] = cur_min
cur_min = math.inf
for i in reversed(range(n)):
cur_min = min(cur_min, nums[i])
min_right[i] = cur_min
min_sum = math.inf
for i in range(1, n - 1):
left, mid, right = min_left[i - 1], nums[i], min_right[i + 1]
if left < mid > right:
min_sum = min(min_sum, left + mid + right)
if min_sum == math.inf:
return -1
return min_sum
179 - 2025-08-21 18:50:35 +0300 MSK
Reshape Data: Concatenate
Links
Code
import pandas as pd
def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame:
return pd.concat([df1, df2], axis=0)
180 - 2025-08-21 18:50:21 +0300 MSK
Find Indices With Index and Value Difference I
Links
Code
class Solution:
def findIndices(self, A: List[int], d: int, valueDifference: int) -> List[int]:
mini = maxi = 0
for i in range(d, len(A)):
if A[i - d] < A[mini]:
mini = i - d
if A[i - d] > A[maxi]:
maxi = i - d
if A[i] - A[mini] >= valueDifference:
return [mini, i]
if A[maxi] - A[i] >= valueDifference:
return [maxi, i]
return [-1, -1]
181 - 2025-08-21 18:45:02 +0300 MSK
Fill Missing Data
Links
Code
import pandas as pd
def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame:
products['quantity'].fillna(0, inplace=True)
return products
182 - 2025-08-21 18:35:19 +0300 MSK
Change Data Type
Links
Code
import pandas as pd
def changeDatatype(students: pd.DataFrame) -> pd.DataFrame:
students = students.astype({'grade': int})
return students
183 - 2025-08-21 18:35:00 +0300 MSK
Longest Unequal Adjacent Groups Subsequence I
Links
Code
class Solution:
def getLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]:
res = [words[0]]
prev = groups[0]
for i in range(1, len(groups)):
cur = groups[i]
if cur == prev:
continue
prev = cur
res.append(words[i])
return res
184 - 2025-08-21 18:34:31 +0300 MSK
Rename Columns
Links
Code
import pandas as pd
def renameColumns(students: pd.DataFrame) -> pd.DataFrame:
students = students.rename(
columns={
"id": "student_id",
"first": "first_name",
"last": "last_name",
"age": "age_in_years",
}
)
return students
185 - 2025-08-21 18:30:25 +0300 MSK
Modify Columns
Links
Code
import pandas as pd
def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame:
employees['salary'] = employees['salary'] * 2
return employees
186 - 2025-08-21 18:30:11 +0300 MSK
Last Visited Integers
Links
Code
class Solution:
def lastVisitedIntegers(self, nums: List[int]) -> List[int]:
enc = []
res = []
m1_cnt = 0
for num in nums:
if num != -1:
m1_cnt = 0
enc.append(num)
continue
m1_cnt += 1
if m1_cnt <= len(enc):
res.append(enc[len(enc) - (m1_cnt - 1) - 1])
else:
res.append(-1)
return res
187 - 2025-08-21 18:24:42 +0300 MSK
Drop Missing Data
Links
Code
import pandas as pd
def dropMissingData(students: pd.DataFrame) -> pd.DataFrame:
students.dropna(subset=['name'], inplace=True)
return students
188 - 2025-08-21 18:24:23 +0300 MSK
Divisible and Non-divisible Sums Difference
Links
Code
class Solution:
def differenceOfSums(self, n: int, m: int) -> int:
al = n * (1 + n) // 2
div = (n // m) * (m + (n - (n % m))) // 2
non_div = al - div
return (al - div) - div
189 - 2025-08-21 18:18:09 +0300 MSK
Drop Duplicate Rows
Links
Code
import pandas as pd
def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame:
customers.drop_duplicates(subset='email', keep='first', inplace=True)
return customers
190 - 2025-08-21 18:17:44 +0300 MSK
Create a New Column
Links
Code
import pandas as pd
def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame:
employees['bonus'] = employees['salary'] * 2
return employees
191 - 2025-08-21 18:17:05 +0300 MSK
Select Data
Links
Code
import pandas as pd
def selectData(students: pd.DataFrame) -> pd.DataFrame:
return students.loc[students["student_id"] == 101, ["name", "age"]]
192 - 2025-08-21 18:16:46 +0300 MSK
Display the First Three Rows
Links
Code
import pandas as pd
def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
return employees.head(3)
193 - 2025-08-21 18:16:25 +0300 MSK
Get the Size of a DataFrame
Links
Code
import pandas as pd
def getDataframeSize(players: pd.DataFrame) -> List:
return [players.shape[0], players.shape[1]]
194 - 2025-08-21 18:16:06 +0300 MSK
Create a DataFrame from List
Links
Code
import pandas as pd
def createDataframe(student_data: List[List[int]]) -> pd.DataFrame:
column_names = ["student_id", "age"]
result_dataframe = pd.DataFrame(student_data, columns=column_names)
return result_dataframe
195 - 2025-08-21 18:15:24 +0300 MSK
Maximum Value of an Ordered Triplet I
Links
Code
from typing import List
class Solution:
def maximumTripletValue(self, nums: List[int]) -> int:
n = len(nums)
if n < 3:
return 0
left_max = [0] * n
left_max[0] = nums[0]
for i in range(1, n):
left_max[i] = max(left_max[i - 1], nums[i])
right_max = [0] * n
right_max[-1] = nums[-1]
for i in reversed(range(1, n - 1)):
right_max[i] = max(right_max[i + 1], nums[i])
ans = 0
for i in range(1, n - 1):
left = left_max[i - 1]
right = right_max[i + 1]
ans = max(ans, (left - nums[i]) * right)
return ans
196 - 2025-08-21 17:56:20 +0300 MSK
Minimum Operations to Collect Elements
Links
Code
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
enc = [False] * (k + 1)
res = 0
rem = k
for num in reversed(nums):
res += 1
if 1 <= num <= k and not enc[num]:
enc[num] = True
rem -= 1
if rem == 0:
return res
raise Exception
197 - 2025-08-21 17:51:03 +0300 MSK
Minimum Right Shifts to Sort the Array
Links
Code
class Solution:
def minimumRightShifts(self, nums: List[int]) -> int:
drop = -1
for i, num in enumerate(nums[1:], 1):
if num > nums[i - 1]:
continue
if drop != -1:
return -1
drop = i
if drop == -1:
return 0
if nums[0] <= nums[-1]:
return -1
return len(nums) - drop
198 - 2025-08-21 17:41:49 +0300 MSK
Points That Intersect With Cars
Links
Code
class Solution:
def numberOfPoints(self, nums: List[List[int]]) -> int:
line = [0] * 102
points_on_line = 0
for start, end in nums:
line[start] += 1
line[end + 1] -= 1
for i in range(1, 102):
line[i] += line[i - 1]
if line[i] != 0:
points_on_line += 1
return points_on_line
199 - 2025-08-21 17:35:46 +0300 MSK
Check if Strings Can be Made Equal With Operations I
Links
Code
class Solution:
def canBeEqual(self, s1: str, s2: str) -> bool:
freqs_even = [0] * 26
freqs_odd = [0] * 26
for i, (char1, char2) in enumerate(zip(s1, s2)):
if i % 2 == 0:
trg = freqs_even
else:
trg = freqs_odd
trg[ord(char1) - 97] += 1
trg[ord(char2) - 97] -= 1
for freq1, freq2 in zip(freqs_even, freqs_odd):
if freq1 != 0 or freq2 != 0:
return False
return True
200 - 2025-08-21 17:31:03 +0300 MSK
Furthest Point From Origin
Links
Code
class Solution:
def furthestDistanceFromOrigin(self, moves: str) -> int:
cnt_left, cnt_right, cnt_any = 0, 0, 0
for char in moves:
if char == "L":
cnt_left += 1
elif char == "R":
cnt_right += 1
else:
cnt_any += 1
if cnt_right > cnt_left:
return cnt_right - cnt_left + cnt_any
return cnt_left - cnt_right + cnt_any
201 - 2025-08-21 17:26:29 +0300 MSK
Check if a String Is an Acronym of Words
Links
Code
class Solution:
def isAcronym(self, words: List[str], s: str) -> bool:
if len(words) != len(s):
return False
for i in range(len(words)):
if words[i][0] != s[i]:
return False
return True
202 - 2025-08-21 17:15:57 +0300 MSK
Max Pair Sum in an Array
Links
Code
class Solution:
def maxSum(self, nums: List[int]) -> int:
freqs = [[] for _ in range(10)]
for num in nums:
dig = 0
orig = num
while num > 0:
dig = max(dig, num % 10)
num //= 10
heapq.heappush(freqs[dig], -orig)
res = -1
for nms in freqs:
if len(nms) < 2:
continue
res = max(res, -(heapq.heappop(nms) + heapq.heappop(nms)))
return res
203 - 2025-08-21 17:07:52 +0300 MSK
Split Strings by Separator
Links
Code
class Solution:
def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]:
res = []
cur = []
for word in words:
for char in itertools.chain(word, separator):
if char != separator:
cur.append(char)
elif cur:
res.append("".join(cur))
cur.clear()
return res
204 - 2025-08-21 17:05:33 +0300 MSK
Check if Array is Good
Links
Code
class Solution:
def isGood(self, nums: list[int]) -> bool:
mx = max(nums)
if len(nums) != mx + 1:
return False
freqs = defaultdict(int)
for num in nums:
freqs[num] += 1
if freqs[mx] != 2:
return False
for i in range(1, mx):
if freqs[i] != 1:
return False
return True
205 - 2025-08-21 17:00:40 +0300 MSK
Sum of Squares of Special Elements
Links
Code
class Solution:
def sumOfSquares(self, nums: List[int]) -> int:
n = len(nums)
res = 0
for i in range(1, int(math.sqrt(n)) + 1):
if n % i != 0:
continue
idx1, idx2 = i - 1, (n // i) - 1
res += nums[idx1] ** 2
if idx2 != idx1:
res += nums[idx2] ** 2
return res
206 - 2025-08-21 16:51:13 +0300 MSK
Sum of Squares of Special Elements
Links
Code
class Solution:
def sumOfSquares(self, nums: List[int]) -> int:
n = len(nums)
res = 0
for i in range(n):
if n % (i + 1) == 0:
res += nums[i] ** 2
return res
207 - 2025-08-21 16:50:01 +0300 MSK
Find the Maximum Achievable Number
Links
Code
class Solution:
def theMaximumAchievableX(self, num: int, t: int) -> int:
return num + (t * 2)
208 - 2025-08-21 16:46:44 +0300 MSK
Longest Alternating Subarray
Links
Code
class Solution:
def alternatingSubarray(self, nums: list[int]) -> int:
n = len(nums)
maxi = 0
for i in range(n - 1):
if nums[i + 1] != nums[i] + 1:
continue
curr, prev = 2, 1
for j in range(i + 2, n):
diff = nums[j] - nums[j - 1]
if diff == -prev:
curr += 1
prev = -prev
else:
break
maxi = max(maxi, curr)
return maxi if maxi > 0 else -1
209 - 2025-08-21 16:44:37 +0300 MSK
Longest Even Odd Subarray With Threshold
Links
Code
class Solution:
def longestAlternatingSubarray(self, nums: list[int], threshold: int) -> int:
n = len(nums)
if n == 1:
if nums[0] % 2 == 0 and nums[0] <= threshold:
return 1
return 0
length = 0
for l in range(n):
if nums[l] % 2 != 0:
continue
for r in range(l, n):
if nums[r] > threshold:
break
ok = True
for i in range(l, r):
if nums[i] % 2 == nums[i + 1] % 2:
ok = False
break
if ok:
length = max(length, r - l + 1)
return length
210 - 2025-08-21 16:42:44 +0300 MSK
Number of Beautiful Pairs
Links
Code
class Solution:
def countBeautifulPairs(self, nums: List[int]) -> int:
def check(num1: int, num2: int) -> bool:
first, last = 0, num2 % 10
while num1 > 0:
first = num1 % 10
num1 //= 10
return math.gcd(first, last) == 1
res = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if check(nums[i], nums[j]):
res += 1
return res
211 - 2025-08-21 16:38:20 +0300 MSK
Find Maximum Number of String Pairs
Links
Code
class Solution:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
enc = set()
res = 0
for word in words:
if word in enc:
res += 1
else:
enc.add(word[::-1])
return res
212 - 2025-08-21 16:26:55 +0300 MSK
Total Distance Traveled
Links
Code
class Solution:
def distanceTraveled(self, mainTank: int, additionalTank: int) -> int:
res = 0
while mainTank > 4:
count = mainTank // 5
res += count * 5
mainTank %= 5
add_count = min(count, additionalTank)
additionalTank -= add_count
mainTank += add_count
res += mainTank
return res * 10
213 - 2025-08-21 16:19:42 +0300 MSK
Neither Minimum nor Maximum
Links
Code
class Solution:
def findNonMinOrMax(self, nums: List[int]) -> int:
nums.sort()
min_val, max_val = nums[0], nums[-1]
if nums[0] == nums[-1]:
return -1
if len(nums) < 3:
return -1
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
val = nums[mid]
if val == min_val:
left = mid + 1
elif val == max_val:
right = mid - 1
return val
return -1
214 - 2025-08-21 16:16:56 +0300 MSK
Check if The Number is Fascinating
Links
Code
class Solution:
def isFascinating(self, n: int) -> bool:
freqs = [False] * 9
for num in (n, n * 2, n * 3):
while num > 0:
dig = num % 10
if dig == 0:
return False
if freqs[dig - 1]:
return False
freqs[dig - 1] = True
num //= 10
return sum(freqs) == 9
215 - 2025-08-21 16:07:01 +0300 MSK
Is Object Empty
Links
Code
/**
* @param {Object|Array} obj
* @return {boolean}
*/
var isEmpty = function(obj) {
if (Array.isArray(obj)) {
return obj.length === 0;
} else {
return Object.keys(obj).length === 0;
}
};
216 - 2025-08-21 16:06:09 +0300 MSK
Calculator with Method Chaining
Links
Code
class Calculator {
/**
* @param {number} value
*/
constructor(value) {
this.result = value
}
/**
* @param {number} value
* @return {Calculator}
*/
add(value){
this.result += value
return this
}
/**
* @param {number} value
* @return {Calculator}
*/
subtract(value){
this.result -= value
return this
}
/**
* @param {number} value
* @return {Calculator}
*/
multiply(value) {
this.result *= value
return this
}
/**
* @param {number} value
* @return {Calculator}
*/
divide(value) {
if(value === 0){
throw new Error("Division by zero is not allowed")
}
this.result /= value
return this
}
/**
* @param {number} value
* @return {Calculator}
*/
power(value) {
this.result **= value
return this
}
/**
* @return {number}
*/
getResult() {
return this.result
}
}
217 - 2025-08-21 16:01:02 +0300 MSK
Interval Cancellation
Links
Code
/**
* @param {Function} fn
* @param {Array} args
* @param {number} t
* @return {Function}
*/
var cancellable = function(fn, args, t) {
fn(...args);
const timer = setInterval(() => fn(...args), t);
const cancelFn = () => clearInterval(timer);
return cancelFn;
};
/**
* const result = [];
*
* const fn = (x) => x * 2;
* const args = [4], t = 35, cancelTimeMs = 190;
*
* const start = performance.now();
*
* const log = (...argsArr) => {
* const diff = Math.floor(performance.now() - start);
* result.push({"time": diff, "returned": fn(...argsArr)});
* }
*
* const cancel = cancellable(log, args, t);
*
* setTimeout(cancel, cancelTimeMs);
*
* setTimeout(() => {
* console.log(result); // [
* // {"time":0,"returned":8},
* // {"time":35,"returned":8},
* // {"time":70,"returned":8},
* // {"time":105,"returned":8},
* // {"time":140,"returned":8},
* // {"time":175,"returned":8}
* // ]
* }, cancelTimeMs + t + 15)
*/
218 - 2025-08-21 15:58:36 +0300 MSK
Sort By
Links
Code
/**
* @param {Array} arr
* @param {Function} fn
* @return {Array}
*/
var sortBy = function(arr, fn) {
return arr.toSorted((a, b) => fn(a) - fn(b));
};
219 - 2025-08-21 15:55:14 +0300 MSK
Add Two Promises
Links
Code
/**
* @param {Promise} promise1
* @param {Promise} promise2
* @return {Promise}
*/
var addTwoPromises = async function(promise1, promise2) {
const [value1, value2] = await Promise.all([promise1, promise2]);
return value1 + value2;
};
// // Example usage:
// var promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20));
// var promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60));
// addTwoPromises(promise1, promise2)
// .then(console.log); // Output: 7
220 - 2025-08-21 15:49:02 +0300 MSK
Semi-Ordered Permutation
Links
Code
class Solution:
def semiOrderedPermutation(self, nums: List[int]) -> int:
i1, i2 = 0, 0
n = len(nums)
for i, num in enumerate(nums):
if num == 1:
i1 = i
elif num == n:
i2 = i
if i1 and i2:
break
res = i1 + (n - i2 - 1)
if i2 < i1:
res -= 1
return res
221 - 2025-08-21 15:45:35 +0300 MSK
Minimize String Length
Links
Code
class Solution:
def minimizedStringLength(self, s: str) -> int:
freqs = [False] * 26
for char in s:
freqs[ord(char) - 97] = True
return sum(freqs)
222 - 2025-08-21 15:42:45 +0300 MSK
Timeout Cancellation
Links
Code
/**
* @param {Function} fn
* @param {Array} args
* @param {number} t
* @return {Function}
*/
const cancellable = function(fn, args, t) {
const timer = setTimeout(() => {
fn(...args)
}, t);
const cancelFn = function() {
clearTimeout(timer);
};
return cancelFn;
};
/**
* const result = []
*
* const fn = (x) => x * 5
* const args = [2], t = 20, cancelT = 50
*
* const log = (...argsArr) => {
* result.push(fn(...argsArr))
* }
*
* const cancel = cancellable(fn, args, t);
*
* setTimeout(() => {
* cancel()
* console.log(result) // [{"time":20,"returned":10}]
* }, cancelT)
*/
223 - 2025-08-21 15:40:49 +0300 MSK
Remove Trailing Zeros From a String
Links
Code
class Solution:
def removeTrailingZeros(self, num: str) -> str:
val = int(num)
while val > 0 and val % 10 == 0:
val //= 10
return str(val)
224 - 2025-08-21 15:37:36 +0300 MSK
To Be Or Not To Be
Links
Code
class Check {
constructor(val) {
this.val = val;
}
toBe(val) {
if (val === this.val) {
return true;
}
throw new Error("Not Equal");
}
notToBe(val) {
if (val !== this.val) {
return true;
}
throw new Error("Equal");
}
}
/**
* @param {string} val
* @return {Object}
*/
var expect = function(val) {
return new Check(val);
};
/**
* expect(5).toBe(5); // true
* expect(5).notToBe(5); // throws "Equal"
*/
225 - 2025-08-21 15:33:15 +0300 MSK
Return Length of Arguments Passed
Links
Code
/**
* @param {...(null|boolean|number|string|Array|Object)} args
* @return {number}
*/
var argumentsLength = function(...args) {
return args.length;
};
/**
* argumentsLength(1, 2, 3); // 3
*/
226 - 2025-08-21 15:32:49 +0300 MSK
Lexicographically Smallest Palindrome
Links
Code
class Solution:
def makeSmallestPalindrome(self, s: str) -> str:
letters = list(s)
for i in range(len(s) // 2):
letters[i] = letters[~i] = min(letters[i], letters[~i])
return ''.join(letters)
227 - 2025-08-21 15:03:03 +0300 MSK
Minimum String Length After Removing Substrings
Links
Code
class Solution:
def minLength(self, s: str) -> int:
stack = []
for char in s:
if not stack or char not in "ABCD":
stack.append(char)
continue
if (
(stack[-1] == "A" and char == "B")
or (stack[-1] == "C" and char == "D")
):
stack.pop()
else:
stack.append(char)
return len(stack)
228 - 2025-08-21 14:57:54 +0300 MSK
Minimum String Length After Removing Substrings
Links
Code
class Solution:
def minLength(self, s: str) -> int:
while "AB" in s or "CD" in s:
s = s.replace("AB", "").replace("CD", "")
return len(s)
229 - 2025-08-21 14:56:18 +0300 MSK
Array Wrapper
Links
Code
/**
* @param {number[]} nums
* @return {void}
*/
var ArrayWrapper = function(nums) {
this.sum = nums.reduce((a, b) => a + b, 0);
this.string = `[${nums.toString()}]`;
};
/**
* @return {number}
*/
ArrayWrapper.prototype.valueOf = function() {
return this.sum;
}
/**
* @return {string}
*/
ArrayWrapper.prototype.toString = function() {
return this.string;
}
/**
* const obj1 = new ArrayWrapper([1,2]);
* const obj2 = new ArrayWrapper([3,4]);
* obj1 + obj2; // 10
* String(obj1); // "[1,2]"
* String(obj2); // "[3,4]"
*/
230 - 2025-08-21 14:52:44 +0300 MSK
Find the Losers of the Circular Game
Links
Code
class Solution:
def circularGameLosers(self, n: int, k: int) -> List[int]:
count = 1
i = 0
enc = set((0, ))
while True:
i = (i + k * count) % n
if i in enc:
break
enc.add(i)
count += 1
res = []
for i in range(n):
if i not in enc:
res.append(i + 1)
return res
231 - 2025-08-21 14:47:10 +0300 MSK
Number of Senior Citizens
Links
Code
class Solution:
def countSeniors(self, details: List[str]) -> int:
count = 0
for detail in details:
if int(detail[-4:-2]) > 60:
count += 1
return count
232 - 2025-08-21 14:44:56 +0300 MSK
Chunk Array
Links
Code
/**
* @param {Array} arr
* @param {number} size
* @return {Array}
*/
var chunk = function(arr, size) {
const chunkedArray = [];
let index = 0;
while (index < arr.length) {
chunkedArray.push(arr.slice(index, index + size));
index += size;
}
return chunkedArray;
};
233 - 2025-08-21 14:42:42 +0300 MSK
Find the Distinct Difference Array
Links
Code
class Solution:
def distinctDifferenceArray(self, nums: List[int]) -> List[int]:
left, right = set(), defaultdict(int)
for num in nums:
right[num] += 1
res = []
for num in nums:
left.add(num)
right[num] -= 1
if right[num] == 0:
del right[num]
res.append(len(left) - len(right))
return res
234 - 2025-08-21 14:32:28 +0300 MSK
Create Hello World Function
Links
Code
/**
* @return {Function}
*/
var createHelloWorld = function() {
return function(...args) {
return "Hello World";
}
};
/**
* const f = createHelloWorld();
* f(); // "Hello World"
*/
235 - 2025-08-21 14:31:55 +0300 MSK
Allow One Function Call
Links
Code
/**
* @param {Function} fn
* @return {Function}
*/
var once = function(fn) {
let called = false;
return function(...args){
if (called) {
return undefined;
}
called = true;
return fn(...args);
}
};
/**
* let fn = (a,b,c) => (a + b + c)
* let onceFn = once(fn)
*
* onceFn(1,2,3); // 6
* onceFn(2,3,6); // returns undefined without calling fn
*/
236 - 2025-08-21 14:30:46 +0300 MSK
Counter II
Links
Code
class Counter {
constructor(init) {
this.init = init;
this.val = init;
}
increment() {
let val = this.val + 1;
this.val = val;
return val;
}
decrement() {
let val = this.val - 1;
this.val = val;
return val;
}
reset() {
let val = this.init;
this.val = val;
return val;
}
}
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function(init) {
return new Counter(init)
};
/**
* const counter = createCounter(5)
* counter.increment(); // 6
* counter.reset(); // 5
* counter.decrement(); // 4
*/
237 - 2025-08-21 14:28:11 +0300 MSK
Determine the Winner of a Bowling Game
Links
Code
class Solution:
def isWinner(self, player1: List[int], player2: List[int]) -> int:
last_10_1, last_10_2 = -10, -10
score = 0
for i, (hit1, hit2) in enumerate(zip(player1, player2)):
mult1, mult2 = 1, 1
if i - last_10_1 < 3:
mult1 = 2
if i - last_10_2 < 3:
mult2 = 2
score += hit1 * mult1 - hit2 * mult2
if hit1 == 10:
last_10_1 = i
if hit2 == 10:
last_10_2 = i
if score > 0:
return 1
elif score < 0:
return 2
return 0
238 - 2025-08-21 14:14:45 +0300 MSK
Maximum Sum With Exactly K Elements
Links
Code
class Solution:
def maximizeSum(self, nums: List[int], k: int) -> int:
first = max(nums)
last = first + (k - 1) * 1
return (k * (first + last)) // 2
239 - 2025-08-21 14:03:34 +0300 MSK
Sum Multiples
Links
Code
class Solution:
def sumOfMultiples(self, n: int) -> int:
enc = set()
for num in range(3, n + 1, 3):
enc.add(num)
for num in range(5, n + 1, 5):
enc.add(num)
for num in range(7, n + 1, 7):
enc.add(num)
return sum(enc)
240 - 2025-08-21 13:59:45 +0300 MSK
Calculate Delayed Arrival Time
Links
Code
class Solution:
def findDelayedArrivalTime(self, arrivalTime: int, delayedTime: int) -> int:
return (arrivalTime + delayedTime) % 24
241 - 2025-08-21 13:58:37 +0300 MSK
Generate Fibonacci Sequence
Links
Code
/**
* @return {Generator<number>}
*/
var fibGenerator = function*() {
let num1 = 0;
let num2 = 1;
yield num1;
yield num2;
while (true) {
const num3 = num1 + num2;
num1 = num2;
num2 = num3;
yield num3;
}
};
/**
* const gen = fibGenerator();
* gen.next().value; // 0
* gen.next().value; // 1
*/
242 - 2025-08-21 13:56:09 +0300 MSK
Find the Maximum Divisibility Score
Links
Code
class Solution:
def maxDivScore(self, nums: List[int], divisors: List[int]) -> int:
freqs = defaultdict(int)
for num in nums:
freqs[num] += 1
divisors.sort()
max_div, max_count = divisors[0], 0
for div in divisors:
count = 0
for num, freq in freqs.items():
if num % div == 0:
count += freq
if count > max_count:
max_div, max_count = div, count
return max_div
243 - 2025-08-21 13:42:53 +0300 MSK
Row With Maximum Ones
Links
Code
class Solution:
def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
max_row, max_count = 0, sum(mat[0])
for i, row in enumerate(mat[1:], 1):
count = sum(row)
if count > max_count:
max_row, max_count = i, count
return max_row, max_count
244 - 2025-08-21 13:40:48 +0300 MSK
Find the Width of Columns of a Grid
Links
Code
class Solution:
def findColumnWidth(self, grid: List[List[int]]) -> List[int]:
res = []
for col in range(len(grid[0])):
max_len = 0
for row in range(len(grid)):
val = grid[row][col]
if val == 0:
count = 1
elif val < 0:
count = 1
val = -val
else:
count = 0
while val > 0:
count += 1
val //= 10
max_len = max(max_len, count)
res.append(max_len)
return res
245 - 2025-08-21 13:31:24 +0300 MSK
Range Sum Query - Mutable
Links
Code
class TreeNode:
def __init__(self, val, start, end, left_child = None, right_child = None):
self.val = val
self.start = start
self.end = end
self.left_child = left_child
self.right_child = right_child
class SegmentTree:
def __init__(self, nums):
self.nums = nums
self.root = self.build(0, len(nums) - 1)
def build(self, start, end):
if start == end:
return TreeNode(self.nums[start], start, end)
left_child = self.build(start, (start + end) //2)
right_child = self.build((start+end) // 2 + 1, end)
return TreeNode(left_child.val + right_child.val, start, end, left_child, right_child)
def update(self, root, index, value):
if root.start == root.end and index == root.start: # target
root.val = value
return value
if root.start > index or root.end < index:
return root.val
root.val = self.update(root.left_child, index, value) + self.update(root.right_child, index, value)
return root.val
def query(self, root, left, right):
if root.start > right or root.end < left: return 0
if root.start >= left and root.end <= right: return root.val
return self.query(root.left_child, left, right) + self.query(root.right_child, left, right)
class NumArray:
def __init__(self, nums: List[int]):
self.tree = SegmentTree(nums)
self.root = self.tree.root
def update(self, index: int, val: int) -> None:
self.tree.update(self.root, index, val)
def sumRange(self, left: int, right: int) -> int:
return self.tree.query(self.root, left, right)
246 - 2025-08-21 13:26:07 +0300 MSK
Online Election
Links
Code
class TopVotedCandidate:
def __init__(self, persons: List[int], times: List[int]):
self._lead = times
freqs = [0] * 5001
prev = persons[0]
freqs[prev] = 1
times[0] = (times[0], prev)
for i in range(1, len(times)):
person = persons[i]
freq = freqs[person] + 1
freqs[person] = freq
if freq >= freqs[prev]:
prev = person
times[i] = (times[i], prev)
def q(self, t: int) -> int:
left, right = 0, len(self._lead) - 1
res = None
while left <= right:
mid = left + (right - left) // 2
lead_time, lead_person = self._lead[mid]
if lead_time > t:
right = mid - 1
elif lead_time == t:
return lead_person
else:
res = lead_person
left = mid + 1
return res
# Your TopVotedCandidate object will be instantiated and called as such:
# obj = TopVotedCandidate(persons, times)
# param_1 = obj.q(t)
247 - 2025-08-21 12:41:54 +0300 MSK
Walking Robot Simulation II
Links
Code
class Robot:
def __init__(self, width: int, height: int):
self.cur = (0, 0)
self.cur_dir = 0
self.width = width
self.height = height
self.dir_mapping = {
0: "East",
1: "North",
2: "West",
3: "South"
}
self.mod = 2 * (self.width + self.height - 2)
def step(self, num: int) -> None:
if num >= self.mod:
num %= self.mod
if self.cur == (0, 0) and self.cur_dir == 0:
self.cur_dir = 3
row, col = self.cur
while num > 0:
if self.cur_dir == 0:
steps = min(num, self.width - row -1)
num -= steps
row += steps
elif self.cur_dir == 1:
steps = min(num, self.height -1 - col)
num -= steps
col += steps
elif self.cur_dir == 2:
steps = min(num, row)
num -= steps
row -= steps
else:
steps = min(num, col)
num -= steps
col -= steps
if num > 0:
self.cur_dir = (self.cur_dir + 1) % 4
self.cur = row, col
def getPos(self) -> List[int]:
return self.cur
def getDir(self) -> str:
return self.dir_mapping[self.cur_dir]
# Your Robot object will be instantiated and called as such:
# obj = Robot(width, height)
# obj.step(num)
# param_2 = obj.getPos()
# param_3 = obj.getDir()
248 - 2025-08-21 12:07:22 +0300 MSK
Number of Beautiful Integers in the Range
Links
Code
class Solution:
def numberOfBeautifulIntegers(self, low: int, high: int, k: int) -> int:
low, hgh = str(low), str(high)
n = len(hgh)
low = low.rjust(n,'0')
@lru_cache(None)
def dfs(idx,
belowHgh,
aboveLow,
init0,
parity,
rem):
if idx == n:
return rem == 0 == parity
lowD, hghD = int(low[idx]), int(hgh[idx])
res = 0
for digit in range(0 if aboveLow else lowD,
(9 if belowHgh else hghD) + 1):
res += dfs(idx + 1,
belowHgh or digit < hghD,
aboveLow or digit > lowD,
init0 and not digit,
parity + digit % 2 - (
not init0 and not digit or
digit and not digit % 2),
(rem * 10 + digit) % k)
return res
return dfs(0, False, False, True, 0, 0)
249 - 2025-08-21 11:45:30 +0300 MSK
Minimum Seconds to Equalize a Circular Array
Links
Code
class Solution:
def minimumSeconds(self, nums: List[int]) -> int:
nums += nums
indices = defaultdict(list)
for i, num in enumerate(nums):
indices[num].append(i)
min_diff = math.inf
for idxs in indices.values():
max_diff = -math.inf
for i1, i2 in itertools.pairwise(idxs):
max_diff = max(max_diff, i2 - i1)
min_diff = min(min_diff, max_diff // 2)
return min_diff
250 - 2025-08-21 11:32:12 +0300 MSK
Longest Arithmetic Subsequence of Given Difference
Links
Code
class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
dp = {}
for num in arr:
prv = num - difference
if prv in dp:
dp[num] = dp[prv] + 1
else:
dp[num] = 1
return max(dp.values())
251 - 2025-08-21 11:29:38 +0300 MSK
Longest Arithmetic Subsequence of Given Difference
Links
Code
class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
n = len(arr)
freqs = defaultdict(list)
for i, num in enumerate(arr):
freqs[num].append(i)
dp = [1] * n
for i in reversed(range(n - 1)):
cur, nxt = arr[i], arr[i] + difference
if nxt not in freqs:
continue
cnt = 0
for j in freqs[nxt]:
if j > i:
cnt = max(cnt, dp[j])
dp[i] = cnt + 1
return max(dp)
252 - 2025-08-21 11:16:33 +0300 MSK
Shortest String That Contains Three Strings
Links
Code
class Solution:
def minimumString(self, a: str, b: str, c: str) -> str:
res, l = '', float('inf')
def merge(s1: str, s2: str) -> str:
if s2 in s1:
return s1
for i in range(len(s1)):
if s2.startswith(s1[i:]):
return s1[:i] + s2
return s1 + s2
for s1, s2, s3 in itertools.permutations((a, b ,c)):
merged = merge(merge(s1, s2), s3)
if len(merged) < l:
res, l = merged, len(merged)
elif len(merged) == l:
res = min(res, merged)
return res
253 - 2025-08-21 11:08:30 +0300 MSK
Design Neighbor Sum Service
Links
Code
class NeighborSum:
def __init__(self, grid: List[List[int]]):
self._adj = [0] * 101
self._diag = [0] * 101
rows, cols = len(grid), len(grid[0])
adj_moves = ((0, 1), (0, -1), (-1, 0), (1, 0))
diag_moves = ((-1, -1), (-1, 1), (1, -1), (1, 1))
for row in range(rows):
for col in range(cols):
val = grid[row][col]
for row_dlt, col_dlt in adj_moves:
adj_row, adj_col = row + row_dlt, col + col_dlt
if 0 <= adj_row < rows and 0 <= adj_col < cols:
self._adj[grid[adj_row][adj_col]] += val
for row_dlt, col_dlt in diag_moves:
diag_row, diag_col = row + row_dlt, col + col_dlt
if 0 <= diag_row < rows and 0 <= diag_col < cols:
self._diag[grid[diag_row][diag_col]] += val
def adjacentSum(self, value: int) -> int:
return self._adj[value]
def diagonalSum(self, value: int) -> int:
return self._diag[value]
# Your NeighborSum object will be instantiated and called as such:
# obj = NeighborSum(grid)
# param_1 = obj.adjacentSum(value)
# param_2 = obj.diagonalSum(value)
254 - 2025-08-21 08:52:21 +0300 MSK
Count Submatrices With All Ones
Links
Code
class Solution:
def numSubmat(self, mat: List[List[int]]) -> int:
heights = [0] * len(mat[0])
res = 0
for row in mat:
for i, x in enumerate(row):
heights[i] = 0 if x == 0 else heights[i] + 1
stack = [[-1, 0, -1]]
for i, h in enumerate(heights):
while stack[-1][2] >= h:
stack.pop()
j, prev, _ = stack[-1]
cur = prev + (i - j) * h
stack.append([i, cur, h])
res += cur
return res
255 - 2025-08-20 20:41:08 +0300 MSK
Apply Transform Over Each Element in Array
Links
Code
/**
* @param {number[]} arr
* @param {Function} fn
* @return {number[]}
*/
var map = function(arr, fn) {
const transformedArr = [];
let index = 0;
for (const element of arr) {
transformedArr[index] = fn(element, index);
index++;
}
return transformedArr;
};
256 - 2025-08-20 20:38:27 +0300 MSK
Filter Elements from Array
Links
Code
/**
* @param {number[]} arr
* @param {Function} fn
* @return {number[]}
*/
var filter = function(arr, fn) {
let res = [];
for (const [i, val] of arr.entries()) {
if (fn(val, i)) {
res.push(val);
}
}
return res;
};
257 - 2025-08-20 20:36:18 +0300 MSK
Function Composition
Links
Code
/**
* @param {Function[]} functions
* @return {Function}
*/
var compose = function(functions) {
if (functions.length === 0) {
return function(x) { return x; };
}
return functions.reduceRight(function(prevFn, nextFn) {
return function(x) {
return nextFn(prevFn(x));
};
});
};
258 - 2025-08-20 20:31:33 +0300 MSK
Array Reduce Transformation
Links
Code
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
let res = init;
for (const num of nums) {
res = fn(res, num);
}
return res;
};
259 - 2025-08-20 20:28:21 +0300 MSK
Sleep
Links
Code
/**
* @param {number} millis
* @return {Promise}
*/
async function sleep(millis) {
return new Promise((resolve) => setTimeout(resolve, millis));
}
/**
* let t = Date.now()
* sleep(100).then(() => console.log(Date.now() - t)) // 100
*/
260 - 2025-08-20 20:26:57 +0300 MSK
Counter
Links
Code
/**
* @param {number} n
* @return {Function} counter
*/
var createCounter = function(n) {
val = n - 1;
return function() {
val += 1;
return val;
};
};
/**
* const counter = createCounter(10)
* counter() // 10
* counter() // 11
* counter() // 12
*/
261 - 2025-08-20 20:25:45 +0300 MSK
Array Prototype Last
Links
Code
/**
* @return {null|boolean|number|string|Array|Object}
*/
Array.prototype.last = function() {
if (this.length > 0) {
return this[this.length - 1];
}
return -1;
};
/**
* const arr = [1, 2, 3];
* arr.last(); // 3
*/
262 - 2025-08-20 20:20:02 +0300 MSK
Prime In Diagonal
Links
Code
class Solution:
def diagonalPrime(self, nums: List[List[int]]) -> int:
def is_prime(num: int) -> int:
if num <= 1:
return 0
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return 0
return num
res = 0
n = len(nums)
for i in range(n):
res = max(res, is_prime(nums[i][i]), is_prime(nums[i][n - i - 1]))
return res
263 - 2025-08-20 20:15:03 +0300 MSK
Find the Longest Balanced Substring of a Binary String
Links
Code
class Solution:
def findTheLongestBalancedSubstring(self, s: str) -> int:
res = 0
cnt_0, cnt_1 = 0, 0
for char in s:
if char == "0":
if cnt_1 != 0:
cnt_0 = 0
cnt_0 += 1
cnt_1 = 0
else:
cnt_1 += 1
res = max(res, min(cnt_0, cnt_1) * 2)
return res
264 - 2025-08-20 20:10:18 +0300 MSK
Form Smallest Number From Two Digit Arrays
Links
Code
class Solution:
def minNumber(self, nums1: List[int], nums2: List[int]) -> int:
freqs1 = [False] * 10
freqs2 = [False] * 10
for num in nums1:
freqs1[num] = True
for num in nums2:
freqs2[num] = True
min1, min2 = None, None
for i in range(10):
if freqs1[i] and freqs2[i]:
return i
if min1 is None and freqs1[i]:
min1 = i
if min2 is None and freqs2[i]:
min2 = i
return min(min1, min2) * 10 + max(min1, min2)
265 - 2025-08-20 19:48:54 +0300 MSK
K Items With the Maximum Sum
Links
Code
class Solution:
def kItemsWithMaximumSum(self, numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int:
res = 0
for val, cnt in ((1, numOnes), (0, numZeros), (-1, numNegOnes)):
if k == 0:
break
cnt = min(k, cnt)
k -= cnt
res += val * cnt
return res
266 - 2025-08-20 19:41:49 +0300 MSK
Distribute Money to Maximum Children
Links
Code
class Solution:
def distMoney(self, money: int, children: int) -> int:
if money < children:
return -1
n = 8 * children - money
if n <= 0:
return children - (n < 0)
ans, rem = divmod(money - children, 7)
return ans - ((ans, rem) == (children - 1, 3))
267 - 2025-08-20 19:24:46 +0300 MSK
Count the Number of Vowel Strings in Range
Links
Code
class Solution:
def vowelStrings(self, words: List[str], left: int, right: int) -> int:
res = 0
vowels = ("a", "e", "i", "o", "u")
for i in range(left, right + 1):
word = words[i]
if word[0] in vowels and word[-1] in vowels:
res += 1
return res
268 - 2025-08-20 19:22:34 +0300 MSK
Pass the Pillow
Links
Code
class Solution:
def passThePillow(self, n, time):
full_rounds = time // (n - 1)
extra_time = time % (n - 1)
if full_rounds % 2 == 0:
return extra_time + 1
else:
return n - extra_time
269 - 2025-08-20 19:11:13 +0300 MSK
Split With Minimum Sum
Links
Code
class Solution:
def splitNum(self, num: int) -> int:
count = 0
digits = []
while num > 0:
digits.append(num % 10)
num //= 10
digits.sort()
res = 0
while digits:
for _ in range(2):
if digits:
res += digits.pop() * (10 ** count)
count += 1
return res
270 - 2025-08-20 19:07:59 +0300 MSK
Left and Right Sum Differences
Links
Code
class Solution:
def leftRightDifference(self, nums: List[int]) -> List[int]:
left, right = 0, sum(nums)
for i in range(len(nums)):
val = nums[i]
right -= val
nums[i] = abs(left - right)
left += val
return nums
271 - 2025-08-20 19:05:44 +0300 MSK
Merge Two 2D Arrays by Summing Values
Links
Code
class Solution:
def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:
freqs = [0] * 1001
for idx, val in itertools.chain(nums1, nums2):
freqs[idx] += val
res = []
for i, freq in enumerate(freqs):
if freq > 0:
res.append((i, freq))
return res
272 - 2025-08-20 19:01:55 +0300 MSK
Maximum Difference by Remapping a Digit
Links
Code
class Solution:
def minMaxDifference(self, num: int) -> int:
s = str(num)
t = s
pos = 0
while pos < len(s) and s[pos] == "9":
pos += 1
if pos < len(s):
s = s.replace(s[pos], "9")
t = t.replace(t[0], "0")
return int(s) - int(t)
273 - 2025-08-20 18:54:48 +0300 MSK
Find the Array Concatenation Value
Links
Code
class Solution:
def findTheArrayConcVal(self, nums: List[int]) -> int:
def concat(num1: int, num2: int) -> int:
res = 0
count = 0
for num in (num2, num1):
while num > 0:
res += (num % 10) * (10 ** count)
count += 1
num //= 10
return res
left, right = 0, len(nums) - 1
res = 0
while left <= right:
num1, num2 = nums[left], nums[right]
if left == right:
res += num1
else:
res += concat(num1, num2)
left += 1
right -= 1
return res
274 - 2025-08-20 18:49:12 +0300 MSK
Take Gifts From the Richest Pile
Links
Code
class Solution:
def pickGifts(self, gifts: List[int], k: int) -> int:
for i in range(len(gifts)):
gifts[i] = -gifts[i]
heapq.heapify(gifts)
for _ in range(k):
val = int(math.sqrt(-heapq.heappop(gifts)))
heapq.heappush(gifts, -val)
return -sum(gifts)
275 - 2025-08-20 18:45:47 +0300 MSK
Separate the Digits in an Array
Links
Code
class Solution:
def separateDigits(self, nums: List[int]) -> List[int]:
res = []
cur = []
for num in nums:
while num > 0:
cur.append(num % 10)
num //= 10
cur.reverse()
res.extend(cur)
cur.clear()
return res
276 - 2025-08-20 18:44:00 +0300 MSK
Count Distinct Numbers on Board
Links
Code
class Solution:
def distinctIntegers(self, n: int) -> int:
if n == 1:
return 1
return n - 1
277 - 2025-08-20 18:28:35 +0300 MSK
Alternating Digit Sum
Links
Code
class Solution:
def alternateDigitSum(self, n: int) -> int:
sign = 1
count = 0
res = 0
while n > 0:
res += (n % 10) * sign
sign *= -1
count += 1
n //= 10
if count % 2 == 0:
return -res
return res
278 - 2025-08-20 18:24:20 +0300 MSK
Difference Between Element Sum and Digit Sum of an Array
Links
Code
class Solution:
def differenceOfSum(self, nums: List[int]) -> int:
el_sum, dig_sum = 0, 0
for num in nums:
el_sum += num
while num > 0:
dig_sum += num % 10
num //= 10
return abs(el_sum - dig_sum)
279 - 2025-08-20 18:23:07 +0300 MSK
Maximum Count of Positive Integer and Negative Integer
Links
Code
class Solution:
def maximumCount(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
start_neg, start_pos = -1, len(nums)
while left <= right:
mid = left + (right - left) // 2
if nums[mid] >= 0:
right = mid - 1
else:
start_neg = mid
left = mid + 1
left, right = start_neg + 1, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] > 0:
start_pos = mid
right = mid - 1
else:
left = mid + 1
return max(start_neg + 1, len(nums) - start_pos)
280 - 2025-08-20 18:22:39 +0300 MSK
Maximum Count of Positive Integer and Negative Integer
Links
Code
class Solution:
def maximumCount(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
start_neg, start_pos = -1, len(nums)
while left <= right:
mid = left + (right - left) // 2
if nums[mid] >= 0:
right = mid - 1
else:
start_neg = mid
left = mid + 1
left, right = start_neg + 1, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] > 0:
start_pos = mid
right = mid - 1
else:
left = mid + 1
print(start_neg, start_pos)
return max(start_neg + 1, len(nums) - start_pos)
281 - 2025-08-20 17:57:07 +0300 MSK
Categorize Box According to Criteria
Links
Code
class Solution:
def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str:
is_bulky = (
max(length, width, height) >= 10 ** 4
or length * width * height >= 10 ** 9
)
is_heavy = mass >= 100
if is_bulky and is_heavy:
return "Both"
if is_bulky and not is_heavy:
return "Bulky"
if is_heavy and not is_bulky:
return "Heavy"
return "Neither"
282 - 2025-08-20 17:48:38 +0300 MSK
Count the Digits That Divide a Number
Links
Code
class Solution:
def countDigits(self, num: int) -> int:
cur = num
res = 0
while cur > 0:
dig = cur % 10
if num % dig == 0:
res += 1
cur //= 10
return res
283 - 2025-08-20 17:47:52 +0300 MSK
Shortest Distance to Target String in a Circular Array
Links
Code
class Solution:
def closestTarget(self, words: List[str], target: str, startIndex: int) -> int:
n = len(words)
for i in range(n):
left, right = (startIndex - i + n) % n, (startIndex + i) % n
if words[left] == target or words[right] == target:
return i
return -1
284 - 2025-08-20 17:43:24 +0300 MSK
Maximum Enemy Forts That Can Be Captured
Links
Code
class Solution:
def captureForts(self, forts: List[int]) -> int:
start = None
max_capt = 0
for i, fort in enumerate(forts):
if fort == 0:
continue
if start is None:
start = i
continue
start_val = forts[start]
if (start_val == 1 and fort == -1) or (start_val == -1 and fort == 1):
max_capt = max(max_capt, i - start - 1)
start = i
return max_capt
285 - 2025-08-20 17:23:29 +0300 MSK
Count Pairs Of Similar Strings
Links
Code
class Solution:
def similarPairs(self, words: List[str]) -> int:
freqs = defaultdict(int)
res = 0
for word in words:
freq = 0
for char in word:
freq |= 1 << (ord(char) - 97)
res += freqs[freq]
freqs[freq] += 1
return res
286 - 2025-08-20 17:18:47 +0300 MSK
Count Pairs Of Similar Strings
Links
Code
class Solution:
def similarPairs(self, words: List[str]) -> int:
freqs = [False] * 26
freqs2 = defaultdict(int)
for word in words:
for char in word:
freqs[ord(char) - 97] = True
freqs2[tuple(freqs)] += 1
for i in range(26):
freqs[i] = False
res = 0
for freq in freqs2.values():
for i in range(freq):
res += (freq - i - 1)
return res
287 - 2025-08-20 15:09:02 +0300 MSK
Delete Greatest Value in Each Row
Links
Code
class Solution:
def deleteGreatestValue(self, grid: List[List[int]]) -> int:
for row in grid:
row.sort()
res = 0
for _ in range(len(grid[0])):
cur_sum = 0
for row in grid:
cur_sum = max(cur_sum, row.pop())
res += cur_sum
return res
288 - 2025-08-20 13:48:16 +0300 MSK
Maximum Value of a String in an Array
Links
Code
class Solution:
def maximumValue(self, strs: List[str]) -> int:
max_val = 0
for s in strs:
if s.isdigit():
val = int(s)
else:
val = len(s)
if val > max_val:
max_val = val
return max_val
289 - 2025-08-20 13:45:38 +0300 MSK
Circular Sentence
Links
Code
class Solution:
def isCircularSentence(self, sentence: str) -> bool:
if sentence[0] != sentence[-1]:
return False
for i, char in enumerate(sentence):
if char == " " and sentence[i - 1] != sentence[i + 1]:
return False
return True
290 - 2025-08-20 13:41:05 +0300 MSK
Minimum Cuts to Divide a Circle
Links
Code
class Solution:
def numberOfCuts(self, n: int) -> int:
if n == 1:
return 0
if n % 2 == 0:
return n // 2
return n
291 - 2025-08-20 13:36:58 +0300 MSK
Number of Unequal Triplets in Array
Links
Code
class Solution:
def unequalTriplets(self, nums: List[int]) -> int:
freqs = [0] * 1001
for num in nums:
freqs[num] += 1
res = 0
left = 0
right = len(nums)
for freq in freqs:
if freq == 0:
continue
right -= freq
res += left * freq * right
left += freq
return res
292 - 2025-08-20 13:29:30 +0300 MSK
Number of Unequal Triplets in Array
Links
Code
class Solution:
def unequalTriplets(self, nums: List[int]) -> int:
freqs = [0] * 1001
for num in nums:
freqs[num] += 1
res = 0
left = 0
right = len(nums)
for freq in freqs:
if freq == 0:
continue
right -= freq
res += left * freq * right
left += freq
return res
293 - 2025-08-20 13:16:55 +0300 MSK
Convert the Temperature
Links
Code
class Solution:
def convertTemperature(self, celsius: float) -> List[float]:
return (celsius + 273.15, (celsius * 1.80 + 32.00))
294 - 2025-08-20 13:13:48 +0300 MSK
Number of Distinct Averages
Links
Code
class Solution:
def distinctAverages(self, nums: List[int]) -> int:
nums.sort()
freqs = [False] * 201
n = len(nums)
res = 0
for i in range(n // 2 + 1):
freq = nums[i] + nums[n - i - 1]
if not freqs[freq]:
res += 1
freqs[freq] = True
return res
295 - 2025-08-20 13:06:17 +0300 MSK
Apply Operations to an Array
Links
Code
class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
n = len(nums)
for i in range(1, n):
cur, prev = nums[i], nums[i - 1]
if prev != 0 and cur == prev:
nums[i], nums[i - 1] = 0, prev * 2
left, right = 0, 1
while left < n and right < n:
num1, num2 = nums[left], nums[right]
if num1 != 0:
left += 1
elif num2 == 0:
right += 1
elif left >= right:
right += 1
else:
nums[left], nums[right] = num2, 0
left += 1
right += 1
return nums
296 - 2025-08-20 12:43:09 +0300 MSK
Average Value of Even Numbers That Are Divisible by Three
Links
Code
class Solution:
def averageValue(self, nums: List[int]) -> int:
res = 0
cnt = 0
for num in nums:
if num % 2 == 0 and num % 3 == 0:
cnt += 1
res += num
if cnt == 0:
return 0
return res // cnt
297 - 2025-08-20 12:38:03 +0300 MSK
Odd String Difference
Links
Code
class Solution:
def oddString(self, words: List[str]) -> str:
freq1, freq2, cur = None, None, []
freq1_word, freq2_word = None, None
freq1_cnt, freq2_cnt = 0, 0
for word in words:
for i in range(1, len(word)):
cur.append(ord(word[i]) - ord(word[i - 1]))
if freq1 is None:
freq1, freq1_word, freq1_cnt = cur, word, 1
cur = []
elif cur == freq1:
freq1_cnt += 1
elif freq2 is None:
freq2, freq2_word, freq2_cnt = cur, word, 1
cur = []
elif cur == freq2:
freq2_cnt += 1
cur.clear()
if min(freq1_cnt, freq2_cnt) == 1 and max(freq1_cnt, freq2_cnt) > 1:
if freq1_cnt == 1:
return freq1_word
return freq2_word
raise Exception
298 - 2025-08-20 12:08:13 +0300 MSK
Count Square Submatrices with All Ones
Links
Code
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
rows, cols = len(matrix), len(matrix[0])
dp = [[0] * (cols + 1) for _ in range(rows + 1)]
res = 0
for row in range(rows):
for col in range(cols):
val = matrix[row][col]
if val == 0:
continue
dp_row, dp_col = row + 1, col + 1
dp_val = min(
dp[dp_row - 1][dp_col],
dp[dp_row][dp_col - 1],
dp[dp_row - 1][dp_col - 1]
) + 1
dp[dp_row][dp_col] = dp_val
res += dp_val
return res
299 - 2025-08-19 20:23:46 +0300 MSK
Determine if Two Events Have Conflict
Links
Code
class Solution:
def haveConflict(self, event1: List[str], event2: List[str]) -> bool:
def parse(clock: str) -> int:
hh, mm = clock[:2], clock[2:]
return hh * 60 + mm
start1, end1 = map(parse, event1)
start2, end2 = map(parse, event2)
if start1 == start2:
return True
if start1 > start2:
return start1 <= end2
return end1 >= start2
300 - 2025-08-19 20:13:25 +0300 MSK
Number of Valid Clock Times
Links
Code
class Solution:
def countTime(self, time: str) -> int:
hh, mm = time.split(':')
count_possible_hours = 1
if (hh == '??'):
count_possible_hours = 24
elif (hh[0] == '?' and int(hh[1]) >= 4):
count_possible_hours = 2
elif (hh[0] == '?' and int(hh[1]) <= 4):
count_possible_hours = 3
elif (int(hh[0]) <= 1 and hh[1] == '?'):
count_possible_hours = 10
elif (int(hh[0]) == 2 and hh[1] == '?'):
count_possible_hours = 4
count_possible_minutes = 1
if (mm == '??'):
count_possible_minutes = 60
elif (mm[0] == '?'):
count_possible_minutes = 6
elif (mm[1] == '?'):
count_possible_minutes = 10
return count_possible_hours * count_possible_minutes
301 - 2025-08-19 20:11:33 +0300 MSK
The Employee That Worked on the Longest Task
Links
Code
class Solution:
def hardestWorker(self, n: int, logs: List[List[int]]) -> int:
max_id, max_dur = logs[0]
for i, (emp_id, leave) in enumerate(logs[1:], 1):
dur = leave - logs[i - 1][1]
if dur > max_dur:
max_id, max_dur = emp_id, dur
elif dur == max_dur and emp_id < max_id:
max_id = emp_id
return max_id
302 - 2025-08-19 20:00:15 +0300 MSK
Number of Common Factors
Links
Code
class Solution:
def commonFactors(self, a: int, b: int) -> int:
res = 0
for i in range(1, min(a, b) + 1):
if a % i == 0 and b % i == 0:
res += 1
return res
303 - 2025-08-19 19:47:47 +0300 MSK
Remove Letter To Equalize Frequency
Links
Code
class Solution:
def equalFrequency(self, word: str) -> bool:
freqs1, freqs2 = defaultdict(int), defaultdict(int)
for char in word:
freqs1[char] += 1
for freq in freqs1.values():
freqs2[freq] += 1
if len(freqs2) == 1:
return next(iter(freqs2.keys())) == 1 or next(iter(freqs2.values())) == 1
if len(freqs2) == 2:
f1, f2 = min(freqs2.keys()), max(freqs2.keys())
return (
f1 + 1 == f2 and freqs2[f2] == 1
) or (
f1 == 1 and freqs2[f1] == 1
)
return False
304 - 2025-08-19 16:10:29 +0300 MSK
Sort the People
Links
Code
class Solution:
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
for i in range(len(names)):
names[i] = (heights[i], names[i])
names.sort(reverse=True)
for i in range(len(names)):
names[i] = names[i][1]
return names
305 - 2025-08-19 15:27:24 +0300 MSK
Smallest Even Multiple
Links
Code
class Solution:
def smallestEvenMultiple(self, n: int) -> int:
if n % 2 == 0:
return n
return n * 2
306 - 2025-08-19 15:24:40 +0300 MSK
Count Days Spent Together
Links
Code
class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def count(date: str) -> int:
month = int(date[:2])
days = int(date[3:])
return sum(months[:month - 1]) + days
return max(0, count(min(leaveAlice, leaveBob)) - count(max(arriveAlice, arriveBob)) + 1)
307 - 2025-08-19 15:04:21 +0300 MSK
Most Frequent Even Element
Links
Code
class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
nums.sort()
max_freq, max_freq_num = 0, -1
cur_freq = 0
prev = -1
for num in nums:
if num % 2 != 0:
continue
if num == prev:
cur_freq += 1
else:
cur_freq, prev = 1, num
if cur_freq > max_freq:
max_freq, max_freq_num = cur_freq, num
return max_freq_num
308 - 2025-08-19 14:58:59 +0300 MSK
Check Distances Between Same Letters
Links
Code
class Solution:
def checkDistances(self, s: str, distance: List[int]) -> bool:
for i, char in enumerate(s):
idx = ord(char) - 97
dist = distance[idx]
if dist == -1:
continue
nxt = i + dist + 1
if nxt >= len(s) or s[nxt] != char:
return False
distance[idx] = -1
return True
309 - 2025-08-19 14:42:34 +0300 MSK
Find Subarrays With Equal Sum
Links
Code
class Solution:
def findSubarrays(self, nums: List[int]) -> bool:
enc = set()
for i in range(1, len(nums)):
val = nums[i] + nums[i - 1]
if val in enc:
return True
enc.add(val)
return False
310 - 2025-08-19 14:37:35 +0300 MSK
Longest Subsequence With Limited Sum
Links
Code
class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
nums.sort()
for i in range(1, len(nums)):
nums[i] += nums[i - 1]
for i in range(len(queries)):
target = queries[i]
count = 0
for num in nums:
if num <= target:
count += 1
else:
break
queries[i] = count
return queries
311 - 2025-08-19 14:29:00 +0300 MSK
Minimum Hours of Training to Win a Competition
Links
Code
class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
res = max(0, sum(energy) - initialEnergy + 1)
for exp in experience:
if initialExperience <= exp:
diff = exp - initialExperience + 1
res += diff
initialExperience += diff
initialExperience += exp
return res
312 - 2025-08-19 14:04:31 +0300 MSK
Minimum Recolors to Get K Consecutive Black Blocks
Links
Code
class Solution:
def minimumRecolors(self, blocks: str, k: int) -> int:
left = 0
num_whites = 0
num_recolors = math.inf
for right in range(len(blocks)):
if blocks[right] == "W":
num_whites += 1
if right - left + 1 == k:
num_recolors = min(num_recolors, num_whites)
if blocks[left] == "W":
num_whites -= 1
left += 1
return num_recolors
313 - 2025-08-19 13:54:21 +0300 MSK
Number of Arithmetic Triplets
Links
Code
class Solution:
def arithmeticTriplets(self, nums: List[int], diff: int) -> int:
freqs = [[] for _ in range(201)]
for i, num in enumerate(nums):
freqs[num].append(i)
length = len(nums)
res = 0
for i in range(length):
num1 = nums[i]
for j in range(i + 1, length):
num2 = nums[j]
if num2 - num1 != diff:
continue
num3 = num2 + diff
if num3 > 200:
continue
for k in freqs[num3]:
if k > j:
res += 1
break
return res
314 - 2025-08-19 13:40:19 +0300 MSK
Merge Similar Items
Links
Code
class Solution:
def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
freqs = [0] * 1001
for val, weight in itertools.chain(items1, items2):
freqs[val] += weight
res = [(num, weight) for num, weight in enumerate(freqs) if weight != 0]
return res
315 - 2025-08-19 13:37:47 +0300 MSK
Merge Similar Items
Links
Code
class Solution:
def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
freqs = [(i, 0) for i in range(1001)]
for val, weight in itertools.chain(items1, items2):
_, cur_weight = freqs[val]
freqs[val] = (val, weight + cur_weight)
freqs.sort(reverse=True, key=lambda val: val[1])
while freqs and freqs[-1][1] == 0:
freqs.pop()
freqs.sort()
return freqs
316 - 2025-08-19 13:11:40 +0300 MSK
Make Array Zero by Subtracting Equal Amounts
Links
Code
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
nums.sort(reverse=True)
res = 0
while nums:
num = nums.pop()
if num == 0:
continue
for i in range(len(nums)):
nums[i] = max(0, nums[i] - num)
res += 1
return res
317 - 2025-08-19 11:34:12 +0300 MSK
Number of Unique Subjects Taught by Each Teacher
Links
Code
SELECT
teacher_id,
COUNT(DISTINCT subject_id) AS "cnt"
FROM
Teacher
GROUP BY
teacher_id
318 - 2025-08-19 09:58:54 +0300 MSK
First Letter to Appear Twice
Links
Code
class Solution:
def repeatedCharacter(self, s: str) -> str:
freqs = [0] * 26
for char in s:
idx = ord(char) - 97
freq = freqs[idx] + 1
if freq == 2:
return char
freqs[idx] = freq
raise Exception
319 - 2025-08-19 08:52:54 +0300 MSK
Best Poker Hand
Links
Code
class Solution:
def bestHand(self, ranks: List[int], suits: List[str]) -> str:
ranks.sort()
suits.sort()
same_suit = 1
cur_same_suit = 1
same_rank = 1
cur_same_rank = 1
for i in range(1, len(ranks)):
if ranks[i] == ranks[i - 1]:
cur_same_rank += 1
same_rank = max(same_rank, cur_same_rank)
else:
cur_same_rank = 1
if suits[i] == suits[i - 1]:
cur_same_suit += 1
same_suit = max(same_suit, cur_same_suit)
else:
cur_same_suit = 1
print(same_suit, same_rank)
if same_suit == 5:
return "Flush"
if same_rank >= 3:
return "Three of a Kind"
if same_rank >= 2:
return "Pair"
return "High Card"
320 - 2025-08-19 08:18:09 +0300 MSK
Number of Zero-Filled Subarrays
Links
Code
class Solution:
def zeroFilledSubarray(self, nums: List[int]) -> int:
res = 0
cur = 0
for num in nums:
if num == 0:
cur += 1
res += cur
elif cur != 0:
cur = 0
return res
321 - 2025-08-18 21:10:17 +0300 MSK
Maximum Number of Pairs in Array
Links
Code
class Solution:
def numberOfPairs(self, nums: List[int]) -> List[int]:
cnt_pair, cnt_rest = 0, 0
nums.sort()
length = len(nums)
i = 0
while i < length:
cur = nums[i]
nxt = nums[i + 1] if i + 1 < length else -1
if nxt == cur:
cnt_pair += 1
i += 2
else:
cnt_rest += 1
i += 1
return cnt_pair, cnt_rest
322 - 2025-08-18 21:06:45 +0300 MSK
Minimum Amount of Time to Fill Cups
Links
Code
class Solution:
def fillCups(self, amount: List[int]) -> int:
res = 0
for i in range(len(amount)):
amount[i] = -amount[i]
heapq.heapify(amount)
while len(amount) > 2:
num1, num2 = heapq.heappop(amount), heapq.heappop(amount)
if num1 < 0 or num2 < 0:
res += 1
if num1 < 0:
num1 += 1
heapq.heappush(amount, num1)
if num2 < 0:
num2 += 1
heapq.heappush(amount, num2)
if len(amount) == 1:
return res - amount[0]
num1, num2 = amount
res += min(-num1, -num2) + abs(num1 - num2)
return res
323 - 2025-08-18 20:23:18 +0300 MSK
Decode the Message
Links
Code
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
subst = [-1] * 26
res = []
count = 0
for char in key:
if char == " ":
continue
idx = ord(char) - 97
if subst[idx] == -1:
subst[idx] = count
count += 1
for char in message:
if char == " ":
val = char
else:
val = chr(subst[ord(char) - 97] + 97)
res.append(val)
return "".join(res)
324 - 2025-08-18 20:18:16 +0300 MSK
Check if Matrix Is X-Matrix
Links
Code
class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
length = len(grid)
for row in range(length):
for col in range(length):
is_diag = row == col or length - row - 1 == col
val = grid[row][col]
if (is_diag and val == 0) or (not is_diag and val != 0):
return False
return True
325 - 2025-08-18 20:07:07 +0300 MSK
Count Asterisks
Links
Code
class Solution:
def countAsterisks(self, s: str) -> int:
start = False
res = 0
for char in s:
if char == "|":
start = not start
elif char == "*" and not start:
res += 1
return res
326 - 2025-08-18 20:04:04 +0300 MSK
Greatest English Letter in Upper and Lower Case
Links
Code
class Solution:
def greatestLetter(self, s: str) -> str:
freqs = [(False, False)] * 26
for char in reversed(s):
if char.islower():
idx = ord(char) - 97
is_lower = True
else:
idx = ord(char) - 65
is_lower = False
enc_lower, enc_upper = freqs[idx]
new_val = (enc_lower or is_lower, enc_upper or not is_lower)
if new_val != (enc_lower, enc_upper):
freqs[idx] = new_val
for i in reversed(range(len(freqs))):
if all(freqs[i]):
return chr(i + 65)
return ""
327 - 2025-08-18 19:52:53 +0300 MSK
Calculate Amount Paid in Taxes
Links
Code
class Solution:
def calculateTax(self, brackets: List[List[int]], income: int) -> float:
tax = prev = 0
for upper, perc in brackets:
if income >= upper:
tax += (upper - prev) * perc / 100
prev = upper
else:
tax += (income - prev) * perc / 100
return tax
return tax
328 - 2025-08-18 19:41:27 +0300 MSK
Strong Password Checker II
Links
Code
class Solution:
def strongPasswordCheckerII(self, password: str) -> bool:
if len(password) < 8:
return False
has_lower, has_upper, has_digit, has_spec = False, False, False, False
prev = None
spec = "!@#$%^&*()-+"
for char in password:
if char.islower():
has_lower = True
elif char.isupper():
has_upper = True
elif char.isdigit():
has_digit = True
elif char in spec:
has_spec = True
if prev is not None and char == prev:
return False
prev = char
return has_lower and has_upper and has_digit and has_spec
329 - 2025-08-18 19:36:10 +0300 MSK
Min Max Game
Links
Code
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
while len(nums) > 1:
length = len(nums) // 2
for i in range(length):
if i % 2 == 0:
nums[i] = min(nums[i * 2], nums[i * 2 + 1])
else:
nums[i] = max(nums[i * 2], nums[i * 2 + 1])
while len(nums) > length:
nums.pop()
return nums[0]
330 - 2025-08-18 19:26:10 +0300 MSK
Rearrange Characters to Make Target String
Links
Code
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
freqs1, freqs2 = [0] * 26, [0] * 26
for char in s:
freqs1[ord(char) - 97] += 1
for char in target:
freqs2[ord(char) - 97] += 1
count = math.inf
for i in range(26):
freq1, freq2 = freqs1[i], freqs2[i]
if freq2 == 0:
continue
cur_count = freq1 // freq2
if cur_count == 0:
return 0
if cur_count < count:
count = cur_count
return count
331 - 2025-08-18 19:21:41 +0300 MSK
Check if Number Has Equal Digit Count and Digit Value
Links
Code
class Solution:
def digitCount(self, num: str) -> bool:
freqs = [0] * 10
for char in num:
freqs[int(char)] += 1
for i, char in enumerate(num):
if freqs[i] != int(char):
return False
return True
332 - 2025-08-18 19:16:20 +0300 MSK
Percentage of Letter in String
Links
Code
class Solution:
def percentageLetter(self, s: str, letter: str) -> int:
count = 0
for char in s:
if char == letter:
count += 1
return (count * 100) // len(s)
333 - 2025-08-18 19:11:33 +0300 MSK
Find Resultant Array After Removing Anagrams
Links
Code
class Solution:
def removeAnagrams(self, words: List[str]) -> List[str]:
freqs1, freqs2 = bytearray(26), bytearray(26)
res = []
for i, word in enumerate(words):
for i in range(26):
freqs2[i] = 0
for char in word:
freqs2[ord(char) - 97] += 1
if i != 0 and freqs1 == freqs2:
continue
freqs1, freqs2 = freqs2, freqs1
res.append(word)
return res
334 - 2025-08-18 19:02:01 +0300 MSK
Find Resultant Array After Removing Anagrams
Links
Code
class Solution:
def removeAnagrams(self, words: List[str]) -> List[str]:
prev = ()
res = []
for word in words:
word_sorted = sorted(word)
if prev != word_sorted:
res.append(word)
prev = word_sorted
return res
335 - 2025-08-18 18:43:22 +0300 MSK
Find the K-Beauty of a Number
Links
Code
class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
digits = []
cur_num = num
while cur_num > 0:
digits.append(cur_num % 10)
cur_num //= 10
digits.reverse()
length = len(digits)
if length < k:
return 0
cur_sum = 0
res = 0
for i in range(k):
cur_sum += digits[i] * (10 ** (k - i - 1))
if num % cur_sum == 0:
res += 1
i = k
while i < length:
cur_sum -= digits[i - k] * (10 ** (k - 1))
cur_sum = cur_sum * 10 + digits[i]
if cur_sum != 0 and num % cur_sum == 0:
res += 1
i += 1
return res
336 - 2025-08-18 15:12:00 +0300 MSK
Remove Digit From Number to Maximize Result
Links
Code
class Solution:
def removeDigit(self, number: str, digit: str) -> str:
last_index = 0
digit_int = int(digit)
for i in range(1, len(number)):
cur, prev = int(number[i]), int(number[i - 1])
if prev == digit_int:
if cur > prev:
return "".join((number[:i-1], number[i:]))
else:
last_index = i - 1
if number[-1] == digit:
last_index = len(number) - 1
return "".join((number[:last_index], number[last_index + 1:]))
337 - 2025-08-18 15:03:06 +0300 MSK
Count Prefixes of a Given String
Links
Code
class Solution:
def countPrefixes(self, words: List[str], s: str) -> int:
res = 0
for word in words:
if s.startswith(word):
res += 1
return res
338 - 2025-08-18 14:55:52 +0300 MSK
Intersection of Multiple Arrays
Links
Code
class Solution:
def intersection(self, nums: List[List[int]]) -> List[int]:
length = len(nums)
freqs = [[False] * length for _ in range(1002)]
for i, arr in enumerate(nums):
for num in arr:
if not freqs[num][i]:
freqs[num][i] = True
nums.clear()
for num, freq in enumerate(freqs):
if all(freq):
nums.append(num)
return nums
339 - 2025-08-18 14:48:14 +0300 MSK
Intersection of Multiple Arrays
Links
Code
class Solution:
def intersection(self, nums: List[List[int]]) -> List[int]:
enc = set(nums[0])
for arr in nums[1:]:
enc.intersection_update(arr)
return sorted(enc)
340 - 2025-08-18 14:43:36 +0300 MSK
Calculate Digit Sum of a String
Links
Code
class Solution:
def digitSum(self, s: str, k: int) -> str:
res, cur, group = list(map(int, s)), [], []
i = 0
def add_digits(num: int) -> None:
if num == 0:
cur.append(0)
return
while num > 0:
group.append(num % 10)
num //= 10
group.reverse()
cur.extend(group)
group.clear()
while len(res) > k:
while i < len(res):
add_digits(sum(res[i:i + k]))
i += k
res, cur = cur, res
cur.clear()
i = 0
return "".join(map(str, res))
341 - 2025-08-18 13:44:46 +0300 MSK
Find Closest Number to Zero
Links
Code
class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
max_diff, max_num = math.inf, 0
for num in nums:
diff = abs(num)
if diff < max_diff or (diff == max_diff and num > max_num):
max_diff, max_num = diff, num
return max_num
342 - 2025-08-18 13:40:40 +0300 MSK
Largest Number After Digit Swaps by Parity
Links
Code
class Solution:
def largestInteger(self, num: int) -> int:
odd, even, digits = [], [], []
while num > 0:
dig = num % 10
if dig % 2 == 0:
heapq.heappush(even, dig)
digits.append(True)
else:
heapq.heappush(odd, dig)
digits.append(False)
num //= 10
res = 0
for i in range(len(digits)):
if digits[i]:
target = even
else:
target = odd
res += heapq.heappop(target) * (10 ** i)
return res
343 - 2025-08-18 13:34:09 +0300 MSK
Largest Number After Digit Swaps by Parity
Links
Code
class Solution:
def largestInteger(self, num: int) -> int:
odd, even, res = [], [], []
while num > 0:
dig = num % 10
if dig % 2 == 0:
even.append(dig)
res.append(True)
else:
odd.append(dig)
res.append(False)
num //= 10
odd.sort(reverse=True)
even.sort(reverse=True)
res.reverse()
length = len(res)
num = 0
for i in reversed(range(length)):
if res[i]:
num += even.pop() * (10 ** (length - i - 1))
else:
num += odd.pop() * (10 ** (length - i - 1))
return num
344 - 2025-08-18 10:06:49 +0300 MSK
24 Game
Links
Code
from typing import List
import math
class Solution:
def judgePoint24(self, cards: List[int]) -> bool:
EPS = 1e-6
def backtrack(nums: List[float]) -> bool:
if len(nums) == 1:
return abs(nums[0] - 24.0) < EPS
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
rest = [nums[k] for k in range(n) if k != i and k != j]
a, b = nums[i], nums[j]
candidates = []
candidates.append(a + b)
candidates.append(a * b)
candidates.append(a - b)
candidates.append(b - a)
if abs(b) > EPS:
candidates.append(a / b)
if abs(a) > EPS:
candidates.append(b / a)
for x in candidates:
if backtrack(rest + [x]):
return True
return False
return backtrack([float(x) for x in cards])
345 - 2025-08-17 20:02:56 +0300 MSK
Minimum Number of Operations to Convert Time
Links
Code
class Solution:
def convertTime(self, current: str, correct: str) -> int:
current_time = 60 * int(current[0:2]) + int(current[3:5])
target_time = 60 * int(correct[0:2]) + int(correct[3:5])
diff = target_time - current_time
count = 0
for i in (60, 15, 5, 1):
count += diff // i
diff %= i
return count
346 - 2025-08-17 19:56:52 +0300 MSK
Divide Array Into Equal Pairs
Links
Code
class Solution:
def divideArray(self, nums: List[int]) -> bool:
nums.sort()
prev = nums[0]
count = 1
for num in nums[1:]:
if num == prev:
count += 1
elif count % 2 != 0:
return False
else:
count = 1
prev = num
return count % 2 == 0
347 - 2025-08-17 19:54:48 +0300 MSK
Divide Array Into Equal Pairs
Links
Code
class Solution:
def divideArray(self, nums: List[int]) -> bool:
freqs = defaultdict(int)
for num in nums:
freqs[num] += 1
for freq in freqs.values():
if freq % 2 != 0:
return False
return True
348 - 2025-08-17 19:44:55 +0300 MSK
Find All K-Distant Indices in an Array
Links
Code
class Solution:
def findKDistantIndices(
self, nums: List[int], key: int, k: int
) -> List[int]:
res = []
right = 0
length = len(nums)
for j in range(length):
if nums[j] != key:
continue
left = max(right, j - k)
right = min(length - 1, j + k) + 1
res.extend(range(left, right))
return res
349 - 2025-08-17 19:21:20 +0300 MSK
Cells in a Range on an Excel Sheet
Links
Code
class Solution:
def cellsInRange(self, s: str) -> List[str]:
cell1, cell2 = s.split(":")
row1, col1 = cell1[0], int(cell1[1:])
row2, col2 = cell2[0], int(cell2[1:])
res = []
while row1 <= row2:
for col in range(col1, col2 + 1):
res.append(f"{row1}{col}")
row1 = chr(ord(row1) + 1)
return res
350 - 2025-08-17 19:15:00 +0300 MSK
Most Frequent Number Following Key In an Array
Links
Code
class Solution:
def mostFrequent(self, nums: List[int], key: int) -> int:
freqs = [0] * 1001
prev = nums[0]
max_freq, max_freq_num = 0, 0
res = 0
for num in nums[1:]:
if prev == key:
freq = freqs[num] + 1
freqs[num] = freq
if freq > max_freq:
max_freq, max_freq_num = freq, num
prev = num
return max_freq_num
351 - 2025-08-17 19:10:32 +0300 MSK
Counting Words With a Given Prefix
Links
Code
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
res = 0
for word in words:
if word.startswith(pref):
res += 1
return res
352 - 2025-08-17 19:08:02 +0300 MSK
Count Integers With Even Digit Sum
Links
Code
class Solution:
def countEven(self, num: int) -> int:
dig_sum = 0
val = num
while val > 0:
dig_sum += val % 10
val //= 10
if dig_sum % 2 == 0:
return num // 2
return (num - 1) // 2
353 - 2025-08-17 18:51:40 +0300 MSK
Count Equal and Divisible Pairs in an Array
Links
Code
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
freqs = tuple([] for i in range(101))
res = 0
for j, num in enumerate(nums):
for i in freqs[num]:
if (i * j) % k == 0:
res += 1
freqs[num].append(j)
return res
354 - 2025-08-17 18:46:10 +0300 MSK
Count Equal and Divisible Pairs in an Array
Links
Code
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
length = len(nums)
res = 0
for i in range(length):
num1 = nums[i]
for j in range(i + 1, length):
if (i * j) % k == 0 and num1 == nums[j]:
res += 1
return res
355 - 2025-08-17 18:44:14 +0300 MSK
Count Equal and Divisible Pairs in an Array
Links
Code
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
length = len(nums)
res = 0
for i in range(length):
num1 = nums[i]
for j in range(i + 1, length):
if num1 == nums[j] and (i * j) % k == 0:
res += 1
return res
356 - 2025-08-17 18:40:15 +0300 MSK
Count Operations to Obtain Zero
Links
Code
class Solution:
def countOperations(self, num1: int, num2: int) -> int:
count = 0
while num1 > 0 and num2 > 0:
if num1 >= num2:
count += num1 // num2
num1 %= num2
else:
count += num2 // num1
num2 %= num1
return count
357 - 2025-08-17 18:38:02 +0300 MSK
Count Operations to Obtain Zero
Links
Code
class Solution:
def countOperations(self, num1: int, num2: int) -> int:
count = 0
while num1 > 0 and num2 > 0:
if num1 >= num2:
num1 -= num2
else:
num2 -= num1
count += 1
return count
358 - 2025-08-17 18:25:12 +0300 MSK
Sort Even and Odd Indices Independently
Links
Code
class Solution:
def sortEvenOdd(self, nums: List[int]) -> List[int]:
odd, even = [], []
for i, num in enumerate(nums):
if i % 2 == 0:
heapq.heappush(even, num)
else:
heapq.heappush(odd, -num)
for i in range(len(nums)):
if i % 2 == 0:
nums[i] = heapq.heappop(even)
else:
nums[i] = -heapq.heappop(odd)
return nums
359 - 2025-08-17 18:16:02 +0300 MSK
Minimum Sum of Four Digit Number After Splitting Digits
Links
Code
class Solution:
def minimumSum(self, num: int) -> int:
digits = []
while num > 0:
digits.append(num % 10)
num //= 10
digits.sort()
return digits[0] * 10 + digits[1] * 10 + digits[2] + digits[3]
360 - 2025-08-17 18:06:00 +0300 MSK
Keep Multiplying Found Values by Two
Links
Code
class Solution:
def findFinalValue(self, nums: List[int], original: int) -> int:
nums.sort()
length = len(nums)
left, right = 0, length - 1
while left <= right:
i = left + (right - left) // 2
val = nums[i]
if val > original:
right = i - 1
elif val == original:
original *= 2
left = i + 1
right = length - 1
else:
left = i + 1
return original
361 - 2025-08-17 17:56:42 +0300 MSK
Keep Multiplying Found Values by Two
Links
Code
class Solution:
def findFinalValue(self, nums: List[int], original: int) -> int:
nums = set(nums)
while original in nums:
original *= 2
return original
362 - 2025-08-17 17:28:49 +0300 MSK
Count Elements With Strictly Smaller and Greater Elements
Links
Code
class Solution:
def countElements(self, nums: List[int]) -> int:
if len(nums) < 3:
return 0
nums.sort()
res = 0
prev, cur, cur_count = None, nums[0], 1
for num in nums:
if num == cur:
cur_count += 1
elif prev is None:
prev = cur
cur = num
cur_count = 1
else:
res += cur_count
prev = cur
cur = num
cur_count = 1
return res
363 - 2025-08-17 17:16:59 +0300 MSK
Minimum Cost of Buying Candies With Discount
Links
Code
class Solution:
def minimumCost(self, cost: List[int]) -> int:
cost.sort()
res = 0
while cost:
if len(cost) > 2:
res += cost.pop() + cost.pop()
cost.pop()
else:
res += cost.pop()
return res
364 - 2025-08-17 17:04:01 +0300 MSK
Divide a String Into Groups of Size k
Links
Code
class Solution:
def divideString(self, s: str, k: int, fill: str) -> List[str]:
res = []
cur = []
for char in s:
cur.append(char)
if len(cur) == k:
res.append("".join(cur))
cur.clear()
if cur and len(cur) < k:
cur.append(fill * (k - len(cur)))
res.append("".join(cur))
cur.clear()
return res
365 - 2025-08-17 16:00:07 +0300 MSK
Check if Every Row and Column Contains All Numbers
Links
Code
class Solution:
def checkValid(self, matrix: List[List[int]]) -> bool:
length = len(matrix)
rows = bytearray(length + 1)
cols = bytearray(length + 1)
for row in range(length):
for col in range(length):
row_col, col_row = matrix[row][col], matrix[col][row]
rows[row_col] += 1
cols[col_row] += 1
if rows[row_col] > 1 or cols[col_row] > 1:
return False
for i in range(length + 1):
rows[i] = 0
cols[i] = 0
return True
366 - 2025-08-17 13:53:56 +0300 MSK
Capitalize the Title
Links
Code
class Solution:
def capitalizeTitle(self, title: str) -> str:
res = []
cur = []
for char in itertools.chain(title, " "):
if char != " ":
cur.append(char)
continue
for i in range(len(cur)):
cur[i] = cur[i].lower()
if len(cur) > 2:
cur[0] = cur[0].upper()
res.append("".join(cur))
cur.clear()
return " ".join(res)
367 - 2025-08-17 13:41:15 +0300 MSK
Check if All A’s Appears Before All B’s
Links
Code
class Solution:
def checkString(self, s: str) -> bool:
found_a = False
found_b = False
for char in s:
if char == "a":
if found_b:
return False
if not found_a:
found_a = True
else:
if not found_b:
found_b = True
return True
368 - 2025-08-17 13:38:02 +0300 MSK
A Number After a Double Reversal
Links
Code
class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if num == 0:
return True
return num % 10 != 0
369 - 2025-08-17 13:36:24 +0300 MSK
Maximum Number of Words Found in Sentences
Links
Code
class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
res = 0
for sentence in sentences:
count = sentence.count(" ") + 1
if count > res:
res = count
return res
370 - 2025-08-17 13:34:11 +0300 MSK
Rings and Rods
Links
Code
class Solution:
def countPoints(self, rings: str) -> int:
rods = [(False, False, False)] * 10
res = 0
for i in range(0, len(rings), 2):
rod = int(rings[i + 1])
color = rings[i]
has_red, has_green, has_blue = rods[rod]
if color == "R":
has_red = True
elif color == "G":
has_green = True
else:
has_blue = True
rods[rod] = (has_red, has_green, has_blue)
for vals in rods:
if all(vals):
res += 1
return res
371 - 2025-08-17 13:25:54 +0300 MSK
Find Subsequence of Length K With the Largest Sum
Links
Code
class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
length = len(nums)
for i in range(length):
nums[i] = (i, nums[i])
nums.sort(key=lambda num: -num[1])
while len(nums) > k:
nums.pop()
nums.sort()
for i in range(k):
nums[i] = nums[i][1]
return nums
372 - 2025-08-17 13:10:43 +0300 MSK
Finding 3-Digit Even Numbers
Links
Code
class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
res = []
freq = Counter(digits)
for i in range(100, 1000, 2):
freq1 = Counter([int(d) for d in str(i)])
if all(freq[d] >= freq1[d] for d in freq1.keys()):
res.append(i)
return res
373 - 2025-08-17 12:55:05 +0300 MSK
Find Target Indices After Sorting Array
Links
Code
class Solution:
def targetIndices(self, nums: List[int], target: int) -> List[int]:
count_eq = 0
count_less = 0
for num in nums:
if num == target:
count_eq += 1
elif num < target:
count_less += 1
return tuple(range(count_less, count_less + count_eq))
374 - 2025-08-17 12:47:03 +0300 MSK
Find Target Indices After Sorting Array
Links
Code
class Solution:
def targetIndices(self, nums: List[int], target: int) -> List[int]:
nums.sort()
if nums[0] > target or nums[-1] < target:
return []
res = []
for i, num in enumerate(nums):
if num == target:
res.append(i)
return res
375 - 2025-08-17 12:39:05 +0300 MSK
Count Common Words With One Occurrence
Links
Code
class Solution:
def countWords(self, words1: List[str], words2: List[str]) -> int:
freqs = defaultdict(lambda: (0, 0))
for word in words1:
freq1, _ = freqs[word]
if freq1 in (0, 1):
freqs[word] = (freq1 + 1, 0)
for word in words2:
freq1, freq2 = freqs[word]
if freq2 in (0, 1):
freqs[word] = (freq1, freq2 + 1)
res = 0
for freq1, freq2 in freqs.values():
if freq1 == freq2 == 1:
res += 1
return res
376 - 2025-08-17 11:54:12 +0300 MSK
Two Furthest Houses With Different Colors
Links
Code
class Solution:
def maxDistance(self, colors: List[int]) -> int:
prev, res = math.inf, 0
start = colors[0]
for i, color in enumerate(colors):
if color != start:
res = i
prev = min(prev, i)
else:
res = max(res, i - prev)
return res
377 - 2025-08-17 09:23:21 +0300 MSK
New 21 Game
Links
Code
class Solution:
def new21Game(self, n: int, k: int, maxPts: int) -> float:
dp = [0] * (n + 1)
dp[0] = 1
s = 1 if k > 0 else 0
for i in range(1, n + 1):
dp[i] = s / maxPts
if i < k:
s += dp[i]
if i - maxPts >= 0 and i - maxPts < k:
s -= dp[i - maxPts]
return sum(dp[k:])
378 - 2025-08-16 18:43:20 +0300 MSK
Check Whether Two Strings are Almost Equivalent
Links
Code
class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
freqs = [0] * 26
for char in word1:
freqs[ord(char) - 97] += 1
for char in word2:
freqs[ord(char) - 97] -= 1
for freq in freqs:
if freq > 3 or freq < -3:
return False
return True
379 - 2025-08-16 16:51:28 +0300 MSK
Count Vowel Substrings of a String
Links
Code
from collections import defaultdict
class Solution:
def countVowelSubstrings(self, word):
vowels_map = {'a': True, 'e': True, 'i': True, 'o': True, 'u': True}
len_word = len(word)
left_index = 0
right_index = 0
ret_val = 0
char_to_freq_map = defaultdict(int)
i = 0
while i < len_word:
c = word[i]
if c in vowels_map.keys():
char_to_freq_map[c] += 1
while set(char_to_freq_map.keys()) == set(vowels_map.keys()):
c = word[right_index]
char_to_freq_map[c] -= 1
if (char_to_freq_map[c] <= 0):
char_to_freq_map.pop(c)
right_index += 1
ret_val += (right_index - left_index)
else:
char_to_freq_map.clear()
left_index = i + 1
right_index = i + 1
i += 1
return ret_val
380 - 2025-08-16 16:11:23 +0300 MSK
Smallest Index With Equal Value
Links
Code
class Solution:
def smallestEqual(self, nums: List[int]) -> int:
for i, num in enumerate(nums):
if i % 10 == num:
return i
return -1
381 - 2025-08-16 14:42:51 +0300 MSK
Kth Distinct String in an Array
Links
Code
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
freqs = defaultdict(int)
for string in arr:
if freqs[string] in (0, 1):
freqs[string] += 1
for string in arr:
if freqs[string] == 1:
if k == 1:
return string
k -= 1
return ""
382 - 2025-08-16 14:31:57 +0300 MSK
Number of Valid Words in a Sentence
Links
Code
class Solution:
def countValidWords(self, sentence: str) -> int:
def is_valid_word(token):
len_token = len(token)
i = 0
while (i < len_token):
c = token[i]
if (ord(c) not in range(ord('a'), ord('z') + 1)
and c != '-'
and c not in ('!', '.', ',')):
return False
elif (c == '-'
and i > 1
and not token[:i].isalpha()):
return False
elif (c == '-'
and i < len_token - 1
and (not token[i+1:].isalpha() and not (token[i+1:-1].isalpha() and token[-1] in ('!', '.', ',')))):
return False
elif (c == '-'
and (i == 0 or i == len_token-1)):
return False
elif (c in ('!', '.', ',')
and i < len_token - 1):
return False
i += 1
return True
tokens = [t for t in sentence.split(' ') if t != '']
count_valid_words = 0
for token in tokens:
print(token, is_valid_word(token))
if (is_valid_word(token)):
count_valid_words += 1
return count_valid_words
383 - 2025-08-16 14:30:59 +0300 MSK
Check if Numbers Are Ascending in a Sentence
Links
Code
class Solution:
def areNumbersAscending(self, s: str) -> bool:
cur = []
prev = 0
for char in itertools.chain(s, " "):
if char.isdigit():
cur.append(char)
elif cur:
val = 0
count = 0
while cur:
val += int(cur.pop()) * (10 ** count)
count += 1
if val <= prev:
return False
prev = val
return True
384 - 2025-08-16 14:27:06 +0300 MSK
Two Out of Three
Links
Code
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
freqs = [(False, False, False)] * 102
for num in nums1:
freqs[num] = (True, False, False)
for num in nums2:
stat1, stat2, _ = freqs[num]
if not stat2:
freqs[num] = (stat1, True, False)
for num in nums3:
stat1, stat2, stat3 = freqs[num]
if not stat3:
freqs[num] = (stat1, stat2, True)
nums1.clear()
for num in range(1, len(freqs)):
if sum(freqs[num]) >= 2:
nums1.append(num)
return nums1
385 - 2025-08-16 14:19:48 +0300 MSK
Minimum Moves to Convert String
Links
Code
class Solution:
def minimumMoves(self, s: str) -> int:
i = 0
length = len(s)
res = 0
while i < length:
if s[i] == "X":
res += 1
i += 3
else:
i += 1
return res
386 - 2025-08-16 14:16:53 +0300 MSK
Convert 1D Array Into 2D Array
Links
Code
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
i = 0
if len(original) != m * n:
return []
res = [[None] * n for _ in range(m)]
for row in range(m):
for col in range(n):
res[row][col] = original[i]
i += 1
return res
387 - 2025-08-16 14:14:34 +0300 MSK
Maximum Difference Between Increasing Elements
Links
Code
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
res, left = -1, nums[0]
for num in nums[1:]:
if num > left:
diff = num - left
if diff > res:
res = diff
else:
left = num
return res
388 - 2025-08-16 14:05:37 +0300 MSK
Final Value of Variable After Performing Operations
Links
Code
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
res = 0
for op in operations:
if op.startswith("++") or op.endswith("++"):
res += 1
else:
res -= 1
return res
389 - 2025-08-16 14:04:12 +0300 MSK
Count Number of Pairs With Absolute Difference K
Links
Code
class Solution:
def countKDifference(self, nums: List[int], k: int) -> int:
freqs = [0] * 102
count = 0
for num in nums:
freqs[num] += 1
for num in nums:
freqs[num] = max(freqs[num] - 1, 0)
target = num + k
for target in (num - k, num + k):
if target >= 0 and target < 102 and freqs[target] > 0:
count += freqs[target]
return count
390 - 2025-08-16 13:53:07 +0300 MSK
Count Special Quadruplets
Links
Code
class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
count = 0
numbers = defaultdict(list)
length = len(nums)
for i in range(length - 1):
for j in range(i + 1, length):
numbers[nums[i] + nums[j]].append(j)
for i in range(2, length - 1):
for j in range(i + 1, length):
target = nums[j] - nums[i]
for idx in numbers[target]:
if i > idx:
count += 1
return count
391 - 2025-08-16 13:39:08 +0300 MSK
Find the Middle Index in Array
Links
Code
class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
left, right = 0, sum(nums)
for i, num in enumerate(nums):
right -= num
if left == right:
return i
left += num
return -1
392 - 2025-08-16 13:35:39 +0300 MSK
Minimum Difference Between Highest and Lowest of K Scores
Links
Code
class Solution:
def minimumDifference(self, nums: list[int], k: int) -> int:
if (k < 2 or k > len(nums)):
return 0
nums.sort()
lowest = float('inf')
for i in range(len(nums) - k + 1):
diff = nums[i + k - 1] - nums[i]
if diff < lowest:
lowest = diff
return lowest
393 - 2025-08-16 13:22:50 +0300 MSK
Find Greatest Common Divisor of Array
Links
Code
class Solution:
def findGCD(self, nums: List[int]) -> int:
nums.sort()
small, big = nums[0], nums[-1]
for i in range(1, small + 1):
if small % i != 0:
continue
val = small // i
if big % val == 0:
return val
raise Exception
394 - 2025-08-16 13:15:31 +0300 MSK
Employees Whose Manager Left the Company
Links
Code
SELECT
employee_id
FROM
Employees
WHERE
manager_id NOT IN (
SELECT
employee_id
FROM
Employees
)
AND salary < 30000
ORDER BY
employee_id
395 - 2025-08-16 13:13:30 +0300 MSK
Minimum Time to Type Word Using Special Typewriter
Links
Code
class Solution:
def minTimeToType(self, word: str) -> int:
pos = 97
res = 0
for char in word:
cur_pos = ord(char)
diff = abs(cur_pos - pos)
res += min(diff, 26 - diff) + 1
pos = cur_pos
return res
396 - 2025-08-16 12:59:52 +0300 MSK
Number of Strings That Appear as Substrings in Word
Links
Code
class Solution:
def numOfStrings(self, patterns: List[str], word: str) -> int:
count = 0
for pattern in patterns:
if pattern in word:
count += 1
return count
397 - 2025-08-16 12:54:52 +0300 MSK
Employees With Missing Information
Links
Code
SELECT
COALESCE(
t1.employee_id,
t2.employee_id
) AS employee_id
FROM
Employees t1
FULL JOIN
Salaries t2
ON
t1.employee_id = t2.employee_id
WHERE
t1.name IS NULL
OR t2.salary IS NULL
ORDER BY
employee_id;
398 - 2025-08-16 12:42:27 +0300 MSK
Check If String Is a Prefix of Array
Links
Code
class Solution:
def isPrefixString(self, s: str, words: List[str]) -> bool:
i = 0
length = len(s)
for word in words:
if i >= length:
return True
word_length = len(word)
if word_length > length - i:
return False
if word != s[i:i+word_length]:
return False
i += word_length
return i >= length
399 - 2025-08-16 12:24:35 +0300 MSK
Three Divisors
Links
Code
class Solution:
def isThree(self, n: int) -> bool:
count = 1
for num in range(2, n // 2 + 1):
if n % num == 0:
count += 2
if count > 3:
break
return count == 3
400 - 2025-08-16 12:19:08 +0300 MSK
Sum of Digits of String After Convert
Links
Code
class Solution:
def getLucky(self, s: str, k: int) -> int:
def trans(val: int, count: int) -> int:
if count == 0:
return val
res = 0
while val > 0:
res += val % 10
val //= 10
return trans(res, count - 1)
val = 0
for char in s:
val += trans(ord(char) - 97 + 1, 1)
return trans(val, k - 1)
401 - 2025-08-16 12:12:54 +0300 MSK
Check if All Characters Have Equal Number of Occurrences
Links
Code
class Solution:
def areOccurrencesEqual(self, s: str) -> bool:
freqs = defaultdict(int)
for char in s:
freqs[char] += 1
target = freqs[s[0]]
for freq in freqs.values():
if freq != target:
return False
return True
402 - 2025-08-16 12:11:17 +0300 MSK
Maximum Number of Words You Can Type
Links
Code
class Solution:
def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
ignore = False
res = 0
for char in itertools.chain(text, " "):
if char == " ":
if ignore:
ignore = False
else:
res += 1
elif char in brokenLetters:
ignore = True
return res
403 - 2025-08-16 12:07:23 +0300 MSK
Concatenation of Array
Links
Code
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
nums.append(nums[i])
return nums
404 - 2025-08-16 12:06:11 +0300 MSK
Count Square Sum Triples
Links
Code
class Solution:
def countTriples(self, n: int) -> int:
res = 0
for a in range(1, n):
for b in range(a + 1, n):
c = math.sqrt(a * a + b * b)
if c % 1 == 0 and c <= n:
res += 2
return res
405 - 2025-08-16 11:58:38 +0300 MSK
Build Array from Permutation
Links
Code
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
length = len(nums)
for i in range(length):
val = nums[i] % 1000
res = 1000 * (nums[val] % 1000)
nums[i] = res + val
for i in range(length):
nums[i] //= 1000
return nums
406 - 2025-08-16 11:50:13 +0300 MSK
Build Array from Permutation
Links
Code
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
res = [None] * len(nums)
for i, num in enumerate(nums):
res[i] = nums[num]
return res
407 - 2025-08-16 11:32:58 +0300 MSK
Remove One Element to Make the Array Strictly Increasing
Links
Code
class Solution:
def canBeIncreasing(self, nums: List[int]) -> bool:
removed = False
length = len(nums)
for i in range(length - 1):
cur, nxt = nums[i], nums[i + 1]
if nxt > cur:
continue
if removed:
return False
removed = True
if (
i > 0 and nums[i - 1] >= nxt
) and (
i + 2 < length and cur >= nums[i + 2]
):
return False
return True
408 - 2025-08-16 11:14:35 +0300 MSK
Check if All the Integers in a Range Are Covered
Links
Code
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
cov = [False] * (right - left + 1)
for start, end in ranges:
for num in range(max(left, start), min(end, right) + 1):
i = num - left
if not cov[i]:
cov[i] = True
return False not in cov
409 - 2025-08-16 11:13:51 +0300 MSK
Check if All the Integers in a Range Are Covered
Links
Code
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
cov = [False] * (right - left + 1)
for start, end in ranges:
for num in range(max(left, start), min(end, right) + 1):
cov[num - left] = True
return False not in cov
410 - 2025-08-16 11:09:17 +0300 MSK
The Latest Login in 2020
Links
Code
SELECT
user_id,
MAX(time_stamp) AS last_stamp
FROM
Logins
WHERE
time_stamp >= '2020-01-01'
AND time_stamp < '2021-01-01'
GROUP BY
user_id
411 - 2025-08-16 10:49:39 +0300 MSK
Determine Whether Matrix Can Be Obtained By Rotation
Links
Code
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
length = len(mat)
count_0, count_90, count_180, count_270 = 0, 0, 0, 0
for i in range(length):
for j in range(length):
val = mat[i][j]
if val == target[i][j]:
count_0 += 1
if val == target[j][length - i - 1]:
count_90 += 1
if val == target[length - i - 1][length - j - 1]:
count_180 += 1
if val == target[length - j - 1][i]:
count_270 += 1
return length * length in {count_0, count_90, count_180, count_270}
412 - 2025-08-16 10:22:08 +0300 MSK
Check if Word Equals Summation of Two Words
Links
Code
class Solution:
def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
def count(word: str) -> int:
length = len(word)
res = 0
for i in reversed(range(length)):
res += (ord(word[i]) - 97) * (10 ** (length - i - 1))
return res
return count(firstWord) + count(secondWord) == count(targetWord)
413 - 2025-08-16 10:19:18 +0300 MSK
Check if Word Equals Summation of Two Words
Links
Code
class Solution:
def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
digits = []
def count(word: str) -> int:
for char in word:
digits.append(ord(char) - 97)
res = 0
count = 0
while digits:
res += digits.pop() * (10 ** count)
count += 1
return res
return count(firstWord) + count(secondWord) == count(targetWord)
414 - 2025-08-16 10:09:43 +0300 MSK
Maximum 69 Number
Links
Code
class Solution:
def maximum69Number (self, num: int) -> int:
digits = []
while num > 0:
digits.append(num % 10)
num //= 10
digits.reverse()
for i in range(len(digits)):
if digits[i] == 6:
digits[i] = 9
break
res = 0
count = 0
while digits:
res += digits.pop() * (10 ** count)
count += 1
return res
415 - 2025-08-15 17:31:44 +0300 MSK
Substrings of Size Three with Distinct Characters
Links
Code
class Solution:
def countGoodSubstrings(self, s: str) -> int:
res = 0
for i in range(len(s) - 2):
char1, char2, char3 = s[i:i+3]
if char1 != char2 and char1 != char3 and char2 != char3:
res += 1
return res
416 - 2025-08-15 16:57:42 +0300 MSK
Calculate Special Bonus
Links
Code
SELECT
employee_id,
(
CASE
WHEN
employee_id % 2 != 0
AND NOT STARTS_WITH(name, 'M')
THEN
salary
ELSE
0
END
) AS "bonus"
FROM
Employees
ORDER BY
employee_id
417 - 2025-08-15 16:43:07 +0300 MSK
Longer Contiguous Segments of Ones than Zeros
Links
Code
class Solution:
def checkZeroOnes(self, s: str) -> bool:
max_length = [0, 0]
cur = 0
prev = -1
for char in s:
val = int(char)
if val == prev:
cur += 1
else:
cur = 1
if cur > max_length[val]:
max_length[val] = cur
prev = val
return max_length[1] > max_length[0]
418 - 2025-08-15 16:35:39 +0300 MSK
Sorting the Sentence
Links
Code
class Solution:
def sortSentence(self, s: str) -> str:
res = [None] * 9
cur = []
for char in s:
if char.isalpha():
cur.append(char)
elif char.isdigit():
res[int(char) - 1] = "".join(cur)
cur.clear()
return " ".join(word for word in res if word is not None)
419 - 2025-08-15 16:30:08 +0300 MSK
Maximum Population Year
Links
Code
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
population = [0] * 102
max_population = 0
for birth, death in logs:
for year in range(birth, death):
i = year - 1950
new_population = population[i] + 1
population[i] = new_population
if new_population > max_population:
max_population = new_population
for i, count in enumerate(population):
if count == max_population:
return 1950 + i
raise Exception
420 - 2025-08-15 16:25:44 +0300 MSK
Minimum Distance to the Target Element
Links
Code
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
length = len(nums)
dist = 0
while dist < length:
left, right = start - dist, start + dist
if left >= 0 and nums[left] == target:
return dist
if right < length and nums[right] == target:
return dist
dist += 1
raise Exception
421 - 2025-08-15 16:20:07 +0300 MSK
Replace All Digits with Characters
Links
Code
class Solution:
def replaceDigits(self, s: str) -> str:
res = []
for i in range(0, len(s) - 1, 2):
char, digit = s[i], int(s[i + 1])
res.append(char)
res.append(chr(ord(char) + digit))
if len(s) % 2 != 0:
res.append(s[-1])
return "".join(res)
422 - 2025-08-15 16:13:25 +0300 MSK
Sum of Digits in Base K
Links
Code
class Solution:
def sumBase(self, n: int, k: int) -> int:
digits = []
while n > 0:
digits.append(n % k)
n //= k
return sum(digits)
423 - 2025-08-15 16:11:57 +0300 MSK
Check if the Sentence Is Pangram
Links
Code
class Solution:
def checkIfPangram(self, sentence: str) -> bool:
freqs = [0] * 26
for char in sentence:
freqs[ord(char) - 97] += 1
return 0 not in freqs
424 - 2025-08-15 16:11:03 +0300 MSK
Minimum Operations to Make the Array Increasing
Links
Code
class Solution:
def minOperations(self, nums: List[int]) -> int:
res = 0
prev = nums[0]
for num in nums[1:]:
if num > prev:
prev = num
else:
new = prev + 1
res += new - num
prev = new
return res
425 - 2025-08-15 16:06:24 +0300 MSK
Truncate Sentence
Links
Code
class Solution:
def truncateSentence(self, s: str, k: int) -> str:
res = s.split(" ")
while len(res) > k:
res.pop()
return " ".join(res)
426 - 2025-08-15 16:05:32 +0300 MSK
Truncate Sentence
Links
Code
class Solution:
def truncateSentence(self, s: str, k: int) -> str:
res = []
cur = []
for char in itertools.chain(s, " "):
if char.isalpha():
cur.append(char)
else:
res.append("".join(cur))
cur.clear()
if len(res) == k:
return " ".join(res)
raise Exception
427 - 2025-08-15 16:03:03 +0300 MSK
Determine Color of a Chessboard Square
Links
Code
class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
col = ord(coordinates[0]) - 97
row = int(coordinates[1])
if row % 2 == 0:
return col % 2 == 0
return col % 2 != 0
428 - 2025-08-15 15:54:30 +0300 MSK
Number of Different Integers in a String
Links
Code
class Solution:
def numDifferentIntegers(self, word: str) -> int:
enc = set()
cur = []
for char in itertools.chain(word, "a"):
if char.isalpha():
if cur:
count = 0
num = 0
while cur:
num += cur.pop() * (10 ** count)
count += 1
enc.add(num)
else:
cur.append(int(char))
return len(enc)
429 - 2025-08-15 15:47:22 +0300 MSK
Maximum Ascending Subarray Sum
Links
Code
class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
max_sum, cur_sum, prev = nums[0], nums[0], nums[0]
for num in nums[1:]:
if num > prev:
cur_sum += num
else:
cur_sum = num
if cur_sum > max_sum:
max_sum = cur_sum
prev = num
return max_sum
430 - 2025-08-15 15:44:11 +0300 MSK
Second Largest Digit in a String
Links
Code
class Solution:
def secondHighest(self, s: str) -> int:
num1, num2 = -1, -1
for char in s:
if not char.isdigit():
continue
num = int(char)
if num > num2:
num1, num2 = num2, num
elif num != num2 and num > num1:
num1 = num
return num1
431 - 2025-08-15 15:38:40 +0300 MSK
Rearrange Products Table
Links
Code
(
SELECT
product_id,
'store1' AS store,
store1 AS price
FROM
Products
WHERE
store1 IS NOT NULL
) UNION (
SELECT
product_id,
'store2' AS store,
store2 AS price
FROM
Products
WHERE
store2 IS NOT NULL
) UNION (
SELECT
product_id,
'store3' AS store,
store3 AS price
FROM
Products
WHERE
store3 IS NOT NULL
)
ORDER BY
product_id,
store;
432 - 2025-08-15 15:32:17 +0300 MSK
Find Center of Star Graph
Links
Code
class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
num1, num2 = edges[0]
num3, num4 = edges[1]
if num1 == num3 or num1 == num4:
return num1
return num2
433 - 2025-08-15 15:28:53 +0300 MSK
Check if One String Swap Can Make Strings Equal
Links
Code
class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
length = len(s1)
if length != len(s2):
return False
i1, i2 = -1, -1
for i, (char1, char2) in enumerate(zip(s1, s2)):
if char1 == char2:
continue
if i1 == -1:
i1 = i
elif i2 == -1:
i2 = i
else:
return False
if i2 == -1:
return False
return s1[i1] == s2[i2] and s1[i2] == s2[i1]
434 - 2025-08-15 15:12:21 +0300 MSK
Primary Department for Each Employee
Links
Code
SELECT
employee_id,
department_id
FROM
(
SELECT
employee_id,
department_id,
primary_flag,
COUNT(employee_id) OVER(
PARTITION BY
employee_id
) AS employee_count
FROM
Employee
) EmployeePartition
WHERE
employee_count = 1
OR primary_flag = 'Y';
435 - 2025-08-15 15:04:18 +0300 MSK
Check if Binary String Has at Most One Segment of Ones
Links
Code
class Solution:
def checkOnesSegment(self, s: str) -> bool:
enc = False
for char in s:
if char == "1":
if enc:
return False
elif not enc:
enc = True
return True
436 - 2025-08-15 15:03:12 +0300 MSK
Check if Binary String Has at Most One Segment of Ones
Links
Code
class Solution:
def checkOnesSegment(self, s: str) -> bool:
enc = False
for char in s[1:]:
if char == "1" and enc:
return False
elif char == "1":
continue
enc = True
return True
437 - 2025-08-15 14:37:22 +0300 MSK
Count Items Matching a Rule
Links
Code
class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
count = 0
for type, color, name in items:
if (
(ruleKey == "type" and ruleValue == type)
or (ruleKey == "color" and ruleValue == color)
or (ruleKey == "name" and ruleValue == name)
):
count += 1
return count
438 - 2025-08-15 14:34:58 +0300 MSK
Recyclable and Low Fat Products
Links
Code
SELECT
Products.product_id
FROM
Products
WHERE
Products.low_fats = 'Y'
AND Products.recyclable = 'Y';
439 - 2025-08-15 14:33:22 +0300 MSK
Check if Array Is Sorted and Rotated
Links
Code
class Solution:
def check(self, nums: List[int]) -> bool:
prev = nums[0]
count = 0
for num in nums[1:]:
if num >= prev:
pass
elif count == 0:
count = 1
else:
return False
prev = num
if count == 0:
return True
return nums[0] >= nums[-1]
440 - 2025-08-15 14:31:10 +0300 MSK
Check if Array Is Sorted and Rotated
Links
Code
class Solution:
def check(self, nums: List[int]) -> bool:
prev = nums[0]
new_start = 0
for num in nums[1:]:
if num >= prev:
pass
elif new_start == 0:
new_start = num
else:
return False
prev = num
if new_start == 0:
return True
return nums[0] >= nums[-1]
441 - 2025-08-15 14:21:42 +0300 MSK
Sum of Unique Elements
Links
Code
class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
enc = [0] * 101
res = 0
for num in nums:
count = enc[num]
if count == 1:
res -= num
enc[num] = 2
elif count == 0:
res += num
enc[num] = 1
return res
442 - 2025-08-15 14:17:27 +0300 MSK
Maximum Number of Balls in a Box
Links
Code
class Solution:
def countBalls(self, lowLimit: int, highLimit: int) -> int:
freqs = [0] * 100
max_freq = 0
for num in range(lowLimit, highLimit + 1):
box = 0
while num > 0:
box += num % 10
num //= 10
freqs[box] += 1
max_freq = max(max_freq, freqs[box])
return max_freq
443 - 2025-08-15 14:14:49 +0300 MSK
Maximum Number of Balls in a Box
Links
Code
class Solution:
def countBalls(self, lowLimit: int, highLimit: int) -> int:
freqs = defaultdict(int)
max_freq = 0
for num in range(lowLimit, highLimit + 1):
box = 0
while num > 0:
box += num % 10
num //= 10
freqs[box] += 1
max_freq = max(max_freq, freqs[box])
return max_freq
444 - 2025-08-15 13:38:16 +0300 MSK
Find Total Time Spent by Each Employee
Links
Code
SELECT
Employees.event_day AS "day",
Employees.emp_id,
SUM(Employees.out_time - Employees.in_time) AS "total_time"
FROM
Employees
GROUP BY
Employees.event_day,
Employees.emp_id
445 - 2025-08-15 13:31:41 +0300 MSK
Latest Time by Replacing Hidden Digits
Links
Code
class Solution:
def maximumTime(self, time: str) -> str:
hours, minutes = time.split(":")
hour1, hour2 = hours
minute1, minute2 = minutes
if hour1 == "?" and hour2 == "?":
hour1, hour2 = "2", "3"
elif hour1 == "?" and hour2 < "4":
hour1 = "2"
elif hour1 == "?":
hour1 = "1"
elif hour1 == "2" and hour2 == "?":
hour2 = "3"
elif hour2 == "?":
hour2 = "9"
if minute1 == "?":
minute1 = "5"
if minute2 == "?":
minute2 = "9"
return ":".join(("".join((hour1, hour2)), "".join((minute1, minute2))))
446 - 2025-08-15 13:23:40 +0300 MSK
The Number of Employees Which Report to Each Employee
Links
Code
SELECT
managers.employee_id,
managers.name,
COUNT(reports.employee_id) AS reports_count,
ROUND(AVG(reports.age)) AS average_age
FROM
Employees managers
INNER JOIN
Employees reports
ON
managers.employee_id = reports.reports_to
GROUP BY
managers.employee_id,
managers.name
ORDER BY
managers.employee_id;
447 - 2025-08-15 13:09:22 +0300 MSK
Find Followers Count
Links
Code
SELECT
Followers.user_id,
COUNT(Followers.user_id) AS followers_count
FROM
Followers
GROUP BY
Followers.user_id
ORDER BY
Followers.user_id ASC;
448 - 2025-08-15 13:07:52 +0300 MSK
Find Followers Count
Links
Code
SELECT
followers1.user_id,
COUNT(DISTINCT followers1.follower_id) AS "followers_count"
FROM
Followers followers1
LEFT JOIN
Followers followers2
ON
followers1.user_id = followers2.user_id
GROUP BY
followers1.user_id;
449 - 2025-08-15 12:54:27 +0300 MSK
Number Of Rectangles That Can Form The Largest Square
Links
Code
class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
max_len, res = 0, 0
for length, width in rectangles:
side = min(length, width)
if side < max_len:
continue
elif side == max_len:
res += 1
else:
max_len = side
res = 1
return res
450 - 2025-08-15 12:49:02 +0300 MSK
Decode XORed Array
Links
Code
class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
prev_encoded = encoded[0]
encoded[0] = first
for i in range(1, len(encoded)):
encoded[i], prev_encoded = prev_encoded ^ encoded[i - 1], encoded[i]
encoded.append(prev_encoded ^ encoded[-1])
return encoded
451 - 2025-08-15 12:36:30 +0300 MSK
Decode XORed Array
Links
Code
class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
prev = first
for i in range(len(encoded)):
prev = encoded[i] ^ prev
encoded[i] = prev
encoded.insert(0, first)
return encoded
452 - 2025-08-15 12:28:46 +0300 MSK
Maximum Units on a Truck
Links
Code
class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda item: item[1])
res = 0
while boxTypes and truckSize > 0:
boxes, units = boxTypes.pop()
count = min(boxes, truckSize)
truckSize -= count
res += count * units
return res
453 - 2025-08-15 12:22:34 +0300 MSK
Reformat Phone Number
Links
Code
class Solution:
def reformatNumber(self, number: str) -> str:
digits = []
for char in number:
if char == " " or char == "-":
continue
digits.append(char)
res = []
digits.reverse()
while len(digits) > 4:
res.append("".join((digits.pop(), digits.pop(), digits.pop())))
length = len(digits)
if length == 4:
res.append("".join((digits.pop(), digits.pop())))
res.append("".join((digits.pop(), digits.pop())))
elif length == 3:
res.append("".join((digits.pop(), digits.pop(), digits.pop())))
elif length == 2:
res.append("".join((digits.pop(), digits.pop())))
return "-".join(res)
454 - 2025-08-15 11:52:01 +0300 MSK
Power of Four
Links
Code
class Solution:
def isPowerOfFour(self, n: int) -> bool:
if n <= 0:
return False
if n & (n - 1) != 0:
return False
while n % 4 == 0:
n //= 4
return n == 1
455 - 2025-08-15 11:51:01 +0300 MSK
Power of Four
Links
Code
class Solution:
def isPowerOfFour(self, n: int) -> bool:
if n <= 0:
return False
while n % 4 == 0:
n //= 4
return n == 1
456 - 2025-08-14 20:09:09 +0300 MSK
Largest 3-Same-Digit Number in String
Links
Code
class Solution:
def largestGoodInteger(self, num: str) -> str:
max_digit = "\0"
for index in range(len(num) - 2):
if num[index] == num[index + 1] == num[index + 2]:
max_digit = max(max_digit, num[index])
if max_digit == "\0":
return ""
return max_digit * 3
457 - 2025-08-13 17:56:30 +0300 MSK
Power of Three
Links
Code
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
return False
while n % 3 == 0:
n //= 3
return n == 1
458 - 2025-08-13 17:55:25 +0300 MSK
Power of Three
Links
Code
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
return False
if n == 1:
return True
while n > 1:
if n % 3 != 0:
return False
n //= 3
return True
459 - 2025-08-12 17:49:12 +0300 MSK
Ways to Express an Integer as Sum of Powers
Links
Code
class Solution:
def numberOfWays(self, n: int, x: int) -> int:
MOD = 10**9 + 7
dp = [0] * (n + 1)
dp[0] = 1
for i in range(1, n + 1):
val = i**x
if val > n:
break
for j in range(n, val - 1, -1):
dp[j] = (dp[j] + dp[j - val]) % MOD
return dp[n]
460 - 2025-08-11 18:03:04 +0300 MSK
Range Product Queries of Powers
Links
Code
class Solution:
def productQueries(self, n: int, queries: List[List[int]]) -> List[int]:
mod = 10**9 + 7
bins, rep = [], 1
while n > 0:
if n % 2 == 1:
bins.append(rep)
n //= 2
rep *= 2
m = len(bins)
results = [[0] * m for _ in range(m)]
for i in range(m):
cur = 1
for j in range(i, m):
cur = cur * bins[j] % mod
results[i][j] = cur
ans = []
for left, right in queries:
ans.append(results[left][right])
return ans
461 - 2025-08-10 13:14:07 +0300 MSK
Daily Leads and Partners
Links
Code
SELECT
DailySales.date_id,
DailySales.make_name,
COUNT(DISTINCT DailySales.lead_id) AS unique_leads,
COUNT(DISTINCT DailySales.partner_id) AS unique_partners
FROM
DailySales
GROUP BY
DailySales.date_id,
DailySales.make_name;
462 - 2025-08-10 13:10:37 +0300 MSK
Invalid Tweets
Links
Code
SELECT
Tweets.tweet_id
FROM
Tweets
WHERE
LENGTH(Tweets.content) > 15
463 - 2025-08-10 13:08:24 +0300 MSK
Goal Parser Interpretation
Links
Code
class Solution:
def interpret(self, command: str) -> str:
stack = []
res = []
for char in command:
if char == ")":
if stack:
res.extend(stack)
stack.clear()
else:
res.append("o")
elif char == "G":
res.append("G")
elif char != "(":
stack.append(char)
return "".join(res)
464 - 2025-08-10 13:03:22 +0300 MSK
Maximum Repeating Substring
Links
Code
class Solution:
def maxRepeating(self, sequence: str, word: str) -> int:
temp, res = word, 0
while temp in sequence:
res += 1
temp += word
return res
465 - 2025-08-10 12:56:18 +0300 MSK
Fix Names in a Table
Links
Code
SELECT
Users.user_id,
UPPER(LEFT(Users.name, 1))
|| LOWER(SUBSTRING(Users.name FROM 2)) AS name
FROM
Users
ORDER BY
Users.user_id;
466 - 2025-08-10 12:52:07 +0300 MSK
Average Time of Process per Machine
Links
Code
SELECT
act1.machine_id,
ROUND(AVG(act2.timestamp - act1.timestamp)::decimal, 3) AS processing_time
FROM
Activity act1,
Activity act2
WHERE
act1.machine_id = act2.machine_id
AND act1.process_id = act2.process_id
AND act1.activity_type = 'start'
AND act2.activity_type = 'end'
GROUP BY
act1.machine_id;
467 - 2025-08-10 12:45:06 +0300 MSK
Defuse the Bomb
Links
Code
class Solution:
def decrypt(self, code: List[int], k: int) -> List[int]:
length = len(code)
result = [0 for _ in range(length)]
if k == 0:
return result
start, end, window_sum = 1, k + 1, 0
if k < 0:
start = length - (-k)
end = length
for i in range(start, end):
window_sum += code[i]
for i in range(length):
result[i] = window_sum
window_sum -= code[start % length]
window_sum += code[end % length]
start += 1
end += 1
return result
468 - 2025-08-10 12:15:52 +0300 MSK
Get Maximum in Generated Array
Links
Code
class Solution:
def getMaximumGenerated(self, n: int) -> int:
if n == 0 or n == 1:
return n
nums = [0] * (n + 1)
nums[1] = 1
res = 1
for i in range(2, n + 1):
if i % 2 == 0:
val = nums[i // 2]
else:
val = nums[i // 2] + nums[(i // 2) + 1]
nums[i] = val
res = max(res, val)
return res
469 - 2025-08-10 11:45:24 +0300 MSK
Check Array Formation Through Concatenation
Links
Code
class Solution:
def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
num_to_piece = {}
for i, nums in enumerate(pieces):
for num in nums:
num_to_piece[num] = i
i = 0
length = len(arr)
while i < length:
num1 = arr[i]
if num1 not in num_to_piece:
return False
piece = pieces[num_to_piece[num1]]
for j, num2 in enumerate(piece):
if i + j >= length:
return False
num1 = arr[i + j]
if num1 != num2:
return False
i += len(piece)
return True
470 - 2025-08-10 11:25:09 +0300 MSK
Sort Array by Increasing Frequency
Links
Code
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
freqs = collections.defaultdict(int)
for num in nums:
freqs[num] += 1
nums.sort(key=lambda val: (freqs[val], -val))
return nums
471 - 2025-08-10 11:14:30 +0300 MSK
Percentage of Users Attended a Contest
Links
Code
WITH total_users AS (
SELECT
COUNT(DISTINCT user_id) AS total_count
FROM
Users
)
SELECT
Register.contest_id,
ROUND(
COUNT(DISTINCT Register.user_id) * 100.0 / total_users.total_count,
2
) AS percentage
FROM
Register
CROSS JOIN
total_users
GROUP BY
Register.contest_id,
total_users.total_count
ORDER BY
percentage DESC,
Register.contest_id;
472 - 2025-08-10 11:02:20 +0300 MSK
Slowest Key
Links
Code
class Solution:
def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
max_key, max_dur = keysPressed[0], releaseTimes[0]
for i, num in enumerate(releaseTimes[1:], 1):
dur = num - releaseTimes[i - 1]
cur_key = keysPressed[i]
if dur > max_dur or (dur == max_dur and cur_key > max_key):
max_dur = dur
max_key = cur_key
return max_key
473 - 2025-08-10 10:27:29 +0300 MSK
Reordered Power of 2
Links
Code
class Solution:
def reorderedPowerOf2(self, n: int) -> bool:
if n > 0 and n & (n - 1) == 0:
return True
def count_digits(num: int, out: list[int]) -> None:
while num > 0:
out.append(num % 10)
num //= 10
out.sort()
target = []
count_digits(n, target)
cur = []
for i in range(31):
cur.clear()
count_digits(1 << i, cur)
if cur == target:
return True
return False
474 - 2025-08-09 16:43:21 +0300 MSK
Mean of Array After Removing Some Elements
Links
Code
class Solution:
def trimMean(self, arr: List[int]) -> float:
arr.sort()
length = len(arr)
interval = length // 20
res = sum(arr[interval:length - interval])
res = (res / (length - interval * 2))
return res
475 - 2025-08-09 16:34:28 +0300 MSK
Crawler Log Folder
Links
Code
class Solution:
def minOperations(self, logs: List[str]) -> int:
depth = 0
for op in logs:
if op == "../":
depth = max(depth - 1, 0)
elif op == "./":
pass
else:
depth += 1
return depth
476 - 2025-08-09 16:31:49 +0300 MSK
Rearrange Spaces Between Words
Links
Code
class Solution:
def reorderSpaces(self, text: str) -> str:
res = []
cur_word = []
space_count = 0
for char in text:
if char == " ":
space_count += 1
if cur_word:
res.append("".join(cur_word))
cur_word.clear()
else:
cur_word.append(char)
if cur_word:
res.append("".join(cur_word))
words = len(res) - 1
if words == 0:
join_str = ""
rem_str = " " * space_count
else:
join_str = " " * (space_count // words)
rem_str = " " * (space_count % words)
return "".join((join_str.join(res), rem_str))
477 - 2025-08-09 16:17:16 +0300 MSK
Sum of All Odd Length Subarrays
Links
Code
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
length = len(arr)
answer = 0
for i, num in enumerate(arr):
left, right = i, length - i - 1
odd_left, odd_right = (left // 2) + 1, (right // 2) + 1
even_left, even_right = (left + 1) // 2, (right + 1) // 2
sub_count = (odd_left * odd_right) + (even_left * even_right)
answer += num * sub_count
return answer
478 - 2025-08-09 15:53:09 +0300 MSK
Sum of All Odd Length Subarrays
Links
Code
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
res = 0
for i in range(len(arr)):
cur_sum = 0
for j in range(i, len(arr)):
cur_sum += arr[j]
if (j - i + 1) % 2 != 0:
res += cur_sum
return res
479 - 2025-08-09 11:14:40 +0300 MSK
Power of Two
Links
Code
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
480 - 2025-08-08 18:19:33 +0300 MSK
Soup Servings
Links
Code
class Solution:
def soupServings(self, n: int) -> float:
m = ceil(n / 25)
dp = collections.defaultdict(dict)
def calculate_dp(i: int, j: int) -> float:
if i <= 0 and j <= 0:
return 0.5
if i <= 0:
return 1.0
if j <= 0:
return 0.0
if i in dp and j in dp[i]:
return dp[i][j]
dp[i][j] = (
calculate_dp(i - 4, j)
+ calculate_dp(i - 3, j - 1)
+ calculate_dp(i - 2, j - 2)
+ calculate_dp(i - 1, j - 3)
) / 4.0
return dp[i][j]
for k in range(1, m + 1):
if calculate_dp(k, k) > 1 - 1e-5:
return 1.0
return calculate_dp(m, m)
481 - 2025-08-07 17:57:34 +0300 MSK
Bank Account Summary II
Links
Code
SELECT
Users.name AS "NAME",
SUM(Transactions.amount) AS "BALANCE"
FROM
Users
LEFT JOIN
Transactions
ON
Users.account = Transactions.account
GROUP BY
Users.account, Users.name
HAVING
SUM(Transactions.amount) > 10000
482 - 2025-08-07 17:15:08 +0300 MSK
Find the Maximum Number of Fruits Collected
Links
Code
class Solution:
def maxCollectedFruits(self, fruits):
n = len(fruits)
ans = sum(fruits[i][i] for i in range(n))
def dp():
prev = [float("-inf")] * n
curr = [float("-inf")] * n
prev[n - 1] = fruits[0][n - 1]
for i in range(1, n - 1):
for j in range(max(n - 1 - i, i + 1), n):
best = prev[j]
if j - 1 >= 0:
best = max(best, prev[j - 1])
if j + 1 < n:
best = max(best, prev[j + 1])
curr[j] = best + fruits[i][j]
prev, curr = curr, prev
return prev[n - 1]
ans += dp()
for i in range(n):
for j in range(i):
fruits[i][j], fruits[j][i] = fruits[j][i], fruits[i][j]
ans += dp()
return ans
483 - 2025-08-06 19:26:47 +0300 MSK
Customer Who Visited but Did Not Make Any Transactions
Links
Code
SELECT
Visits.customer_id,
COUNT(Visits.visit_id) AS "count_no_trans"
FROM
Visits
LEFT JOIN
Transactions
ON
Visits.visit_id = Transactions.visit_id
WHERE
Transactions.visit_id IS NULL
GROUP BY
Visits.customer_id
484 - 2025-08-06 16:17:09 +0300 MSK
Fruits Into Baskets III
Links
Code
class Solution:
def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int:
length = len(baskets)
section_length = int(math.sqrt(length))
sections = (length + section_length - 1) // section_length
count = 0
sections_max = [0] * sections
for i in range(length):
section = i // section_length
sections_max[section] = max(sections_max[section], baskets[i])
for fruit in fruits:
unset = 1
for section in range(sections):
if sections_max[section] < fruit:
continue
choose = 0
sections_max[section] = 0
for i in range(section_length):
pos = section * section_length + i
if pos < length and baskets[pos] >= fruit and not choose:
baskets[pos] = 0
choose = 1
if pos < length:
sections_max[section] = max(sections_max[section], baskets[pos])
unset = 0
break
count += unset
return count
485 - 2025-08-05 20:11:10 +0300 MSK
Fruits Into Baskets II
Links
Code
class Solution:
def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int:
count = 0
length = len(baskets)
for fruit in fruits:
unset = 1
for i in range(length):
if fruit <= baskets[i]:
baskets[i] = 0
unset = 0
break
count += unset
return count
486 - 2025-08-04 19:06:02 +0300 MSK
Fruit Into Baskets
Links
Code
class Solution:
def totalFruit(self, fruits: list[int]) -> int:
start = 0
max_len = 0
fruit_count = defaultdict(int)
for end in range(len(fruits)):
fruit_count[fruits[end]] += 1
while len(fruit_count) > 2:
fruit_count[fruits[start]] -= 1
if fruit_count[fruits[start]] == 0:
del fruit_count[fruits[start]]
start += 1
max_len = max(max_len, end - start + 1)
return max_len
487 - 2025-08-03 16:36:16 +0300 MSK
Replace All ?’s to Avoid Consecutive Repeating Characters
Links
Code
class Solution:
def modifyString(self, s: str) -> str:
res = list(s)
length = len(s)
for i in range(length):
char = res[i]
if char != "?":
continue
for char_ascii in string.ascii_lowercase:
if (
(i > 0 and res[i - 1] == char_ascii)
or (i < length - 1 and res[i + 1] == char_ascii)
):
continue
res[i] = char_ascii
break
return "".join(res)
488 - 2025-08-03 16:21:01 +0300 MSK
Matrix Diagonal Sum
Links
Code
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
length = len(mat)
res = 0
for i in range(length):
row1, col1 = i, i
row2, col2 = i, length - i - 1
res += mat[row1][col1]
if row2 != row1 or col2 != col1:
res += mat[row2][col2]
return res
489 - 2025-08-03 16:03:54 +0300 MSK
Detect Pattern of Length M Repeated K or More Times
Links
Code
class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
length = len(arr)
if length < m * k:
return False
for i in range(length - m + 1):
cur_pat = arr[i:i+m]
count = 1
for j in range(i + m, length, m):
if arr[j:j+m] == cur_pat:
count += 1
else:
break
if count >= k:
return True
return False
490 - 2025-08-03 15:13:16 +0300 MSK
Most Visited Sector in a Circular Track
Links
Code
class Solution:
def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
start_sector, end_sector = rounds[0], rounds[-1]
if start_sector <= end_sector:
return tuple(range(start_sector, end_sector + 1))
return tuple(
itertools.chain(
range(1, end_sector + 1),
range(start_sector, n + 1)
)
)
491 - 2025-08-03 15:01:18 +0300 MSK
Thousand Separator
Links
Code
class Solution:
def thousandSeparator(self, n: int) -> str:
if n < 1000:
return str(n)
res = []
count = 0
while n > 0:
res.append(str(n % 10))
count += 1
n //= 10
if count % 3 == 0 and n > 0:
res.append(".")
res.reverse()
return "".join(res)
492 - 2025-08-03 14:57:57 +0300 MSK
Three Consecutive Odds
Links
Code
class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
count = 0
for num in arr:
if num % 2 == 0:
count = 0
else:
count += 1
if count == 3:
return True
return False
493 - 2025-08-03 14:56:16 +0300 MSK
Kth Missing Positive Number
Links
Code
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
prev = 0
for num in arr:
diff = num - prev - 1
if k > diff:
k -= diff
else:
return prev + k
prev = num
return prev + k
494 - 2025-08-03 14:39:49 +0300 MSK
Shuffle String
Links
Code
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
res = [None] * len(s)
for i, char in zip(indices, s):
res[i] = char
return "".join(res)
495 - 2025-08-03 14:36:46 +0300 MSK
Patients With a Condition
Links
Code
SELECT
Patients.patient_id,
Patients.patient_name,
Patients.conditions
FROM
Patients
WHERE
Patients.conditions ~ '(^|\s)DIAB1'
496 - 2025-08-03 14:33:50 +0300 MSK
Water Bottles
Links
Code
class Solution:
def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
res = 0
empty = 0
while numBottles > 0:
res += numBottles
empty += numBottles
numBottles = empty // numExchange
empty %= numExchange
return res
497 - 2025-08-03 14:29:35 +0300 MSK
Find Users With Valid E-Mails
Links
Code
SELECT
*
FROM
Users
WHERE
Users.mail ~ '^[a-zA-Z][a-zA-Z0-9\.\-_]*@leetcode\.com$';
498 - 2025-08-03 14:27:36 +0300 MSK
Reformat Date
Links
Code
class Solution:
def reformatDate(self, date: str) -> str:
day_str, mnth_str, year_str = date.split()
if len(day_str) == 3:
day = int(day_str[0:1])
else:
day = int(day_str[0:2])
mnth = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].index(mnth_str) + 1
year = int(year_str)
return f"{year}-{mnth:02}-{day:02}"
499 - 2025-08-03 14:18:22 +0300 MSK
Can Make Arithmetic Progression From Sequence
Links
Code
class Solution:
def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
arr.sort()
diff = abs(arr[0] - arr[1])
for i in range(1, len(arr) - 1):
if abs(arr[i] - arr[i+1]) != diff:
return False
return True
500 - 2025-08-03 14:14:27 +0300 MSK
Group Sold Products By The Date
Links
Code
SELECT
Activities.sell_date,
COUNT(
DISTINCT (Activities.product, Activities.sell_date)
) AS num_sold,
STRING_AGG(
DISTINCT Activities.product, ',' ORDER BY product
) AS products
FROM
Activities
GROUP BY
Activities.sell_date
ORDER BY
Activities.sell_date;
501 - 2025-08-03 13:56:55 +0300 MSK
Final Prices With a Special Discount in a Shop
Links
Code
class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
stack = deque()
for i in range(len(prices)):
price = prices[i]
while True:
if not stack:
break
last_i, last_price = stack[-1]
if last_price >= price:
prices[last_i] -= price
stack.pop()
else:
break
stack.append((i, price))
return prices
502 - 2025-08-03 13:42:44 +0300 MSK
Shuffle the Array
Links
Code
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
res = []
for j in range(n, 2 * n):
res.extend((nums[j - n], nums[j]))
return res
503 - 2025-08-03 13:35:23 +0300 MSK
Make Two Arrays Equal by Reversing Subarrays
Links
Code
class Solution:
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
freqs = defaultdict(int)
length = len(target)
if length != len(arr):
return False
for i in range(length):
freqs[target[i]] += 1
freqs[arr[i]] -= 1
for count in freqs.values():
if count != 0:
return False
return True
504 - 2025-08-03 13:30:55 +0300 MSK
Check If a Word Occurs As a Prefix of Any Word in a Sentence
Links
Code
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
for i, word in enumerate(sentence.split()):
if word.startswith(searchWord):
return i + 1
return -1
505 - 2025-08-03 13:25:11 +0300 MSK
Consecutive Characters
Links
Code
class Solution:
def maxPower(self, s: str) -> int:
prev = s[0]
count = 1
max_count= 1
for char in s[1:]:
if char == prev:
count += 1
max_count = max(max_count, count)
else:
count = 1
prev = char
return max_count
506 - 2025-08-03 13:22:53 +0300 MSK
Check If All 1’s Are at Least Length K Places Away
Links
Code
class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
prev = -k - 1
for i, num in enumerate(nums):
if num == 0:
continue
if i - prev - 1 >= k:
prev = i
else:
return False
return True
507 - 2025-08-03 13:19:10 +0300 MSK
Reformat The String
Links
Code
class Solution:
def reformat(self, s: str) -> str:
res, digits, al = [""], [], []
for char in s:
if char.isalpha():
al.append(char)
else:
digits.append(char)
while digits and al:
res.extend((digits.pop(), al.pop()))
if digits:
res.append(digits.pop())
elif al:
res[0] = al.pop()
if digits or al:
return ""
return "".join(res)
508 - 2025-08-03 11:38:37 +0300 MSK
Minimum Value to Get Positive Step by Step Sum
Links
Code
class Solution:
def minStartValue(self, nums: List[int]) -> int:
min_sum = float('inf')
cur_sum = 0
for num in nums:
cur_sum += num
min_sum = min(min_sum, cur_sum)
return max(1 - min_sum, 1)
509 - 2025-08-03 10:42:15 +0300 MSK
String Matching in an Array
Links
Code
class Solution:
class TrieNode:
def __init__(self):
# Tracks how many times this substring appears in the Trie.
self.frequency = 0
# Maps characters to their respective child nodes.
self.child_nodes = {}
def stringMatching(self, words: List[str]) -> List[str]:
matching_words = []
root = self.TrieNode() # Initialize the root of the Trie.
# Insert all suffixes of each word into the Trie.
for word in words:
for start_index in range(len(word)):
# Insert each suffix starting from index start_index.
self._insert_word(root, word[start_index:])
# Check each word to see if it exists as a substring in the Trie.
for word in words:
if self._is_substring(root, word):
matching_words.append(word)
return matching_words
def _insert_word(self, root: "TrieNode", word: str) -> None:
current_node = root
for char in word:
if char not in current_node.child_nodes:
# Create a new node if the character does not exist.
current_node.child_nodes[char] = self.TrieNode()
current_node = current_node.child_nodes[char]
current_node.frequency += 1 # Increment the frequency of the node.
def _is_substring(self, root: "TrieNode", word: str) -> bool:
current_node = root
for char in word:
# Traverse the Trie following the characters of the word.
current_node = current_node.child_nodes[char]
# A word is a substring if its frequency in the Trie is greater than 1.
return current_node.frequency > 1
510 - 2025-08-03 10:26:28 +0300 MSK
Maximum Fruits Harvested After at Most K Steps
Links
Code
class Solution:
def maxTotalFruits(
self, fruits: List[List[int]], startPos: int, k: int
) -> int:
n = len(fruits)
sum_ = [0] * (n + 1)
indices = [0] * n
for i in range(n):
sum_[i + 1] = sum_[i] + fruits[i][1]
indices[i] = fruits[i][0]
ans = 0
for x in range(k // 2 + 1):
# move left x steps, then right (k - 2x) steps
y = k - 2 * x
left = startPos - x
right = startPos + y
start = bisect_left(indices, left)
end = bisect_right(indices, right)
ans = max(ans, sum_[end] - sum_[start])
# move right x steps, then left (k - 2x) steps
y = k - 2 * x
left = startPos - y
right = startPos + x
start = bisect_left(indices, left)
end = bisect_right(indices, right)
ans = max(ans, sum_[end] - sum_[start])
return ans
511 - 2025-08-02 20:09:46 +0300 MSK
Top Travellers
Links
Code
SELECT
Users.name,
COALESCE(SUM(Rides.distance), 0) AS "travelled_distance"
FROM
Users
LEFT JOIN
Rides
ON
Users.id = Rides.user_id
GROUP BY
Users.id, Users.name
ORDER BY
travelled_distance DESC,
Users.name ASC
512 - 2025-08-02 20:03:30 +0300 MSK
Minimum Subsequence in Non-Increasing Order
Links
Code
class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
max_sum = sum(nums)
nums.sort(reverse=True)
cur_sum = 0
res = []
for num in nums:
cur_sum += num
res.append(num)
if cur_sum > max_sum - cur_sum:
break
return res
513 - 2025-08-02 19:58:48 +0300 MSK
Count Largest Group
Links
Code
class Solution:
def countLargestGroup(self, n: int) -> int:
freqs = defaultdict(int)
def count(num: int) -> int:
res = 0
while num > 0:
res += num % 10
num //= 10
return res
max_freq = 0
for i in range(1, n + 1):
group = count(i)
freq = freqs[group] + 1
freqs[group] = freq
if freq > max_freq:
max_freq = freq
res = 0
for freq in freqs.values():
if freq == max_freq:
res += 1
return res
514 - 2025-08-02 19:54:21 +0300 MSK
Find Lucky Integer in an Array
Links
Code
class Solution:
def findLucky(self, arr: List[int]) -> int:
freqs = defaultdict(int)
for num in arr:
freqs[num] += 1
max_num = -1
for num, freq in freqs.items():
if num == freq:
max_num = max(max_num, num)
return max_num
515 - 2025-08-02 19:50:44 +0300 MSK
Create Target Array in the Given Order
Links
Code
class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
res = []
for i, num in zip(index, nums):
res.insert(i, num)
return res
516 - 2025-08-02 19:45:12 +0300 MSK
Lucky Numbers in a Matrix
Links
Code
class Solution:
def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
rows = len(matrix)
cols = len(matrix[0])
min_row = float("-inf")
max_col = float("inf")
for row in range(rows):
min_row = max(min_row, min(matrix[row]))
for col in range(cols):
cur_max_col = float("-inf")
for row in range(rows):
cur_max_col = max(cur_max_col, matrix[row][col])
max_col = min(max_col, cur_max_col)
if min_row == max_col:
return [min_row]
return []
517 - 2025-08-02 19:36:06 +0300 MSK
Lucky Numbers in a Matrix
Links
Code
class Solution:
def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
rows = len(matrix)
cols = len(matrix[0])
min_row = [None] * rows
max_col = [None] * cols
for row in range(rows):
min_row[row] = min(matrix[row])
for col in range(cols):
num_max = float("-inf")
for row in range(rows):
num = matrix[row][col]
if num > num_max:
num_max = num
max_col[col] = num_max
res = []
for row in range(rows):
for col in range(cols):
num = matrix[row][col]
if num == min_row[row] and num == max_col[col]:
res.append(num)
return res
518 - 2025-08-02 19:28:39 +0300 MSK
Replace Employee ID With The Unique Identifier
Links
Code
SELECT
EmployeeUNI.unique_id, Employees.name
FROM
Employees
LEFT JOIN
EmployeeUNI
ON
Employees.id = EmployeeUNI.id
519 - 2025-08-02 19:24:42 +0300 MSK
Generate a String With Characters That Have Odd Counts
Links
Code
class Solution:
def generateTheString(self, n: int) -> str:
if n % 2 == 0:
return ("a" * (n - 1)) + "b"
return "a" * n
520 - 2025-08-02 19:22:20 +0300 MSK
Increasing Decreasing String
Links
Code
class Solution:
def sortString(self, s: str) -> str:
freqs = defaultdict(int)
for char in s:
freqs[char] += 1
keys = list(freqs.keys())
keys.sort(key = ord)
length = len(keys)
res = []
while freqs:
for i in itertools.chain(range(length), reversed(range(length))):
key = keys[i]
if key not in freqs:
continue
res.append(key)
freqs[key] -= 1
if freqs[key] == 0:
freqs.pop(key)
return "".join(res)
521 - 2025-08-02 19:12:42 +0300 MSK
How Many Numbers Are Smaller Than the Current Number
Links
Code
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
num_to_count = {}
for i, num in enumerate(sorted(nums)):
if num not in num_to_count:
num_to_count[num] = i
for i in range(len(nums)):
nums[i] = num_to_count[nums[i]]
return nums
522 - 2025-08-02 19:08:24 +0300 MSK
Number of Days Between Two Dates
Links
Code
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
year1, month1, day1 = map(int, date1.split('-'))
year2, month2, day2 = map(int, date2.split('-'))
date1 = datetime.date(year1, month1, day1)
date2 = datetime.date(year2, month2, day2)
return abs((date2 - date1).days)
523 - 2025-08-02 18:59:52 +0300 MSK
Check If N and Its Double Exist
Links
Code
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
enc = set()
for num in arr:
if num == 0 and 0 in enc:
return True
if num % 2 == 0 and num // 2 in enc:
return True
if num * 2 in enc:
return True
enc.add(num)
return False
524 - 2025-08-02 18:49:48 +0300 MSK
Remove Palindromic Subsequences
Links
Code
class Solution:
def removePalindromeSub(self, s: str) -> int:
if s == s[::-1]:
return 1
return 2
525 - 2025-08-02 18:45:57 +0300 MSK
Rank Transform of an Array
Links
Code
class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
num_to_rank = defaultdict(int)
nums = sorted(set(arr))
for rank, num in enumerate(nums, 1):
num_to_rank[num] = rank
for i in range(len(arr)):
arr[i] = num_to_rank[arr[i]]
return arr
526 - 2025-08-02 18:40:13 +0300 MSK
Rank Transform of an Array
Links
Code
class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
ind = defaultdict(list)
for i, num in enumerate(arr):
ind[num].append(i)
for rank, num in enumerate(sorted(ind.keys()), 1):
for i in ind[num]:
arr[i] = rank
return arr
527 - 2025-08-02 18:33:48 +0300 MSK
List the Products Ordered in a Period
Links
Code
SELECT
Products.product_name, SUM(Orders.unit) as "unit"
FROM
Products
JOIN
Orders
ON
Orders.product_id = Products.product_id
WHERE
Orders.order_date BETWEEN '2020-02-01' AND '2020-02-29'
GROUP BY
Products.product_name
HAVING
SUM(Orders.unit) >= 100;
528 - 2025-08-02 18:22:51 +0300 MSK
Maximum 69 Number
Links
Code
class Solution:
def maximum69Number(self, num: int) -> int:
digits = []
while num > 0:
digits.append(num % 10)
num //= 10
digits.reverse()
res = 0
enc = False
length = len(digits)
for i, digit in enumerate(digits):
if digit == 6 and not enc:
digit = 9
enc = True
res += (10 ** (length - i - 1)) * digit
return res
529 - 2025-08-02 18:14:37 +0300 MSK
Convert Integer to the Sum of Two No-Zero Integers
Links
Code
class Solution:
def getNoZeroIntegers(self, n: int) -> List[int]:
if n <= 10:
return [1, n - 1]
def check(num: int) -> bool:
while num > 0:
if num % 10 == 0:
return False
num //= 10
return True
for i in range(1, (n + 1) // 2):
num1, num2 = i, n - i
if check(num1) and check(num2):
return [num1, num2]
raise Exception
530 - 2025-08-02 18:07:54 +0300 MSK
Decompress Run-Length Encoded List
Links
Code
class Solution:
def decompressRLElist(self, nums: List[int]) -> List[int]:
res = []
i = 0
length = len(nums)
while i < length:
freq, val = nums[i], nums[i + 1]
i += 2
res.extend((val, ) * freq)
return res
531 - 2025-08-02 18:04:04 +0300 MSK
Decrypt String from Alphabet to Integer Mapping
Links
Code
class Solution:
def freqAlphabets(self, s: str) -> str:
res = []
length = len(s)
i = 0
while i < length:
if i + 2 < length and s[i + 2] == "#":
res.append(chr(int(s[i:i+2]) + 97 - 1))
i += 3
else:
res.append(chr(int(s[i]) + 97 - 1))
i += 1
return "".join(res)
532 - 2025-08-02 17:59:03 +0300 MSK
Find N Unique Integers Sum up to Zero
Links
Code
class Solution:
def sumZero(self, n: int) -> List[int]:
if n == 1:
return [0]
res = []
if n % 2 != 0:
res.append(0)
n -= 1
for i in range(1, (n // 2) + 1):
res.extend((i, -i))
return res
533 - 2025-08-02 17:54:14 +0300 MSK
Replace Elements with Greatest Element on Right Side
Links
Code
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
greatest = -1
for i in reversed(range(len(arr))):
current = arr[i]
arr[i] = greatest
if current > greatest:
greatest = current
return arr
534 - 2025-08-02 17:28:54 +0300 MSK
Find Numbers with Even Number of Digits
Links
Code
class Solution:
def findNumbers(self, nums: List[int]) -> int:
def count(num: int) -> int:
res = 0
while num:
res += 1
num //= 10
return res
res = 0
for num in nums:
if count(num) % 2 == 0:
res += 1
return res
535 - 2025-08-02 17:26:28 +0300 MSK
Convert Binary Number in a Linked List to Integer
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, head: Optional[ListNode]) -> int:
res = 0
while head:
res <<= 1
res |= head.val
head = head.next
return res
536 - 2025-08-02 17:24:46 +0300 MSK
Students and Examinations
Links
Code
SELECT
Students.student_id,
Students.student_name,
Subjects.subject_name,
COUNT(Examinations.subject_name) as "attended_exams"
FROM
Students
CROSS JOIN
Subjects
LEFT JOIN
Examinations
ON
Students.student_id = Examinations.student_id
AND Subjects.subject_name = Examinations.subject_name
GROUP BY
Students.student_id,
Students.student_name,
Subjects.subject_name
ORDER BY
Students.student_id,
Subjects.subject_name
537 - 2025-08-02 17:06:00 +0300 MSK
Find Winner on a Tic Tac Toe Game
Links
Code
class Solution:
def tictactoe(self, moves: List[List[int]]) -> str:
cols = [[0] * 3 for _ in range(2)]
rows = [[0] * 3 for _ in range(2)]
diags = [[0] * 2 for _ in range(2)]
players = ["A", "B"]
for i, (row, col) in enumerate(moves):
if i % 2 == 0:
player = 0
else:
player = 1
rows[player][row] += 1
cols[player][col] += 1
if row == col:
diags[player][0] += 1
if row == 2 - col:
diags[player][1] += 1
for player in range(2):
for win in (cols, rows, diags):
if 3 in win[player]:
return players[player]
if len(moves) == 9:
return "Draw"
return "Pending"
538 - 2025-08-02 16:50:59 +0300 MSK
Shift 2D Grid
Links
Code
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
if not grid or not grid[0]:
return grid
row_length = len(grid)
col_length = len(grid[0])
num_count = row_length * col_length
k %= num_count
res = [[0] * col_length for _ in range(row_length)]
for row in range(row_length):
for col in range(col_length):
flat_mat_index = (row * col_length) + col
new_flat_mat_index = (flat_mat_index + k) % num_count
new_row = new_flat_mat_index // col_length
new_col = new_flat_mat_index % col_length
res[new_row][new_col] = grid[row][col]
return res
539 - 2025-08-02 16:38:17 +0300 MSK
Cells with Odd Values in a Matrix
Links
Code
class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
mat = [[0] * n for _ in range(m)]
for row, col in indices:
for cur_col in range(n):
mat[row][cur_col] += 1
for cur_row in range(m):
mat[cur_row][col] += 1
count = 0
for row in range(m):
for col in range(n):
if mat[row][col] % 2 != 0:
count += 1
return count
540 - 2025-08-02 16:29:04 +0300 MSK
Rearranging Fruits
Links
Code
class Solution:
def minCost(self, basket1: List[int], basket2: List[int]) -> int:
freq = Counter()
m = float("inf")
for b1 in basket1:
freq[b1] += 1
m = min(m, b1)
for b2 in basket2:
freq[b2] -= 1
m = min(m, b2)
merge = []
for k, c in freq.items():
if c % 2 != 0:
return -1
merge.extend([k] * (abs(c) // 2))
if not merge:
return 0
merge.sort()
return sum(min(2 * m, x) for x in merge[: len(merge) // 2])
541 - 2025-08-02 16:25:49 +0300 MSK
Average Selling Price
Links
Code
SELECT
Prices.product_id,
CASE
WHEN
SUM(UnitsSold.units) is null
THEN
0
ELSE
ROUND(SUM(UnitsSold.units * Prices.price) / SUM(UnitsSold.units)::numeric, 2)
END AS average_price
FROM
Prices
LEFT JOIN
UnitsSold
ON
UnitsSold.product_id = Prices.product_id
AND UnitsSold.purchase_date
BETWEEN Prices.start_date AND Prices.end_date
GROUP BY
Prices.product_id;
542 - 2025-08-02 16:11:25 +0300 MSK
Check If It Is a Straight Line
Links
Code
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
x1, y1 = coordinates[0]
x2, y2 = coordinates[1]
for x3, y3 in coordinates[2:]:
if (x3 - x1) * (y2 - y1) != (x2 - x1) * (y3 - y1):
return False
return True
543 - 2025-08-02 16:04:47 +0300 MSK
Split a String in Balanced Strings
Links
Code
class Solution:
def balancedStringSplit(self, s: str) -> int:
count_l, count_r = 0, 0
count = 0
for char in s:
if char == "R":
count_r += 1
else:
count_l += 1
if count_l == count_r:
count += 1
return count
544 - 2025-08-02 15:56:06 +0300 MSK
Minimum Cost to Move Chips to The Same Position
Links
Code
class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
length = len(position)
odd, even = 0, 0
for pos in position:
if pos % 2 == 0:
even += 1
else:
odd += 1
return min(odd, even)
545 - 2025-08-02 15:46:47 +0300 MSK
Queries Quality and Percentage
Links
Code
SELECT
query_name,
ROUND(SUM(rating * 1.0 / position) / COUNT(*), 2) AS quality,
ROUND(
COUNT(CASE WHEN rating < 3 THEN 1 END) * 1.0 / COUNT(*),
4
) * 100 AS poor_query_percentage
FROM
Queries
GROUP BY
query_name;
546 - 2025-08-02 15:43:09 +0300 MSK
Minimum Absolute Difference
Links
Code
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
min_diff = float("inf")
res = []
for i, num in enumerate(arr[:-1]):
nxt = arr[i + 1]
diff = abs(nxt - num)
if diff < min_diff:
res.clear()
res.append((num, nxt))
min_diff = diff
elif diff == min_diff:
res.append((num, nxt))
return res
547 - 2025-08-02 15:41:03 +0300 MSK
Minimum Absolute Difference
Links
Code
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
min_diff = float("inf")
diffs = defaultdict(list)
for i, num in enumerate(arr[:-1]):
nxt = arr[i + 1]
diff = abs(nxt - num)
diffs[diff].append((num, nxt))
min_diff = min(min_diff, diff)
return diffs[min_diff]
548 - 2025-08-02 15:39:53 +0300 MSK
Minimum Absolute Difference
Links
Code
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
min_diff = float("inf")
res = []
for i, num in enumerate(arr[:-1]):
nxt = arr[i + 1]
diff = abs(nxt - num)
min_diff = min(min_diff, diff)
for i, num in enumerate(arr[:-1]):
nxt = arr[i + 1]
diff = abs(nxt - num)
if diff == min_diff:
res.append((num, nxt))
return res
549 - 2025-08-02 15:34:16 +0300 MSK
Maximum Number of Balloons
Links
Code
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
freqs = defaultdict(int)
for char in text:
freqs[char] += 1
res = min(
freqs["b"],
freqs["a"],
freqs["l"] // 2,
freqs["o"] // 2,
freqs["n"]
)
return res
550 - 2025-08-02 15:27:49 +0300 MSK
Day of the Week
Links
Code
class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
return [
"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday",
"Sunday"
][datetime.date(year, month, day).weekday()]
551 - 2025-08-02 15:19:46 +0300 MSK
Distance Between Bus Stops
Links
Code
class Solution:
def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
length = len(distance)
forward_dist, back_dist = 0, 0
forward, back = start, start
while True:
if forward == destination:
return forward_dist
if back == destination or length + back == destination:
return back_dist
forward_dist += distance[forward]
forward = (forward + 1) % length
back_dist += distance[back - 1]
back -= 1
raise Exception
552 - 2025-08-02 15:01:25 +0300 MSK
Reformat Department Table
Links
Code
SELECT id,
SUM(
CASE
WHEN
month = 'Jan'
THEN
revenue
ELSE
NULL
END
) AS Jan_Revenue,
SUM(
CASE
WHEN
month = 'Feb'
THEN
revenue
ELSE
NULL
END
) AS Feb_Revenue,
SUM(
CASE
WHEN
month = 'Mar'
THEN
revenue
ELSE
NULL
END
) AS Mar_Revenue,
SUM(
CASE
WHEN
month = 'Apr'
THEN
revenue
ELSE
NULL
END
) AS Apr_Revenue,
SUM(
CASE
WHEN
month = 'May'
THEN
revenue
ELSE
NULL
END
) AS May_Revenue,
SUM(
CASE
WHEN
month = 'Jun'
THEN
revenue
ELSE
NULL
END
) AS Jun_Revenue,
SUM(
CASE
WHEN
month = 'Jul'
THEN
revenue
ELSE
NULL
END
) AS Jul_Revenue,
SUM(
CASE
WHEN
month = 'Aug'
THEN
revenue
ELSE
NULL
END
) AS Aug_Revenue,
SUM(
CASE
WHEN
month = 'Sep'
THEN
revenue
ELSE
NULL
END
) AS Sep_Revenue,
SUM(
CASE
WHEN
month = 'Oct'
THEN
revenue
ELSE
NULL
END
) AS Oct_Revenue,
SUM(
CASE
WHEN
month = 'Nov'
THEN
revenue
ELSE
NULL
END
) AS Nov_Revenue,
SUM(
CASE
WHEN
month = 'Dec'
THEN
revenue
ELSE
NULL
END
) AS Dec_Revenue
FROM
Department
GROUP BY
id;
553 - 2025-08-02 14:54:02 +0300 MSK
Prime Arrangements
Links
Code
class Solution:
def numPrimeArrangements(self, n: int) -> int:
prime = [True] * (n + 1)
prime[0] = prime[1] = False
for i in range(2, int(n ** 0.5) + 1):
if not prime[i]:
continue
for j in range(i * i, n + 1, i):
prime[j] = False
prime_count = sum(prime)
mod = 10**9 + 7
fact_primes = math.factorial(prime_count)
fact_norm = math.factorial(n - prime_count)
return (fact_primes * fact_norm) % mod
554 - 2025-08-02 14:25:28 +0300 MSK
Day of the Year
Links
Code
class Solution:
def dayOfYear(self, date: str) -> int:
year, month, day = map(int, date.split('-'))
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
days_in_month[1] = 29
day_number = sum(days_in_month[:month - 1]) + day
return day_number
555 - 2025-08-02 14:21:50 +0300 MSK
Article Views I
Links
Code
SELECT DISTINCT
views1.author_id as "id"
FROM
Views views1
CROSS JOIN
Views views2
WHERE
views1.author_id = views2.viewer_id
AND views1.author_id = views2.author_id
ORDER BY
views1.author_id ASC
556 - 2025-08-02 14:15:20 +0300 MSK
User Activity for the Past 30 Days I
Links
Code
SELECT
activity_date AS day,
COUNT(DISTINCT(user_id)) AS active_users
FROM
Activity
WHERE
activity_date
BETWEEN '2019-07-27'::DATE - INTERVAL '29 DAYS'
AND '2019-07-27'::DATE
GROUP BY
activity_date
557 - 2025-08-02 14:10:21 +0300 MSK
Number of Equivalent Domino Pairs
Links
Code
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
freqs = [0] * 100
res = 0
for num1, num2 in dominoes:
if num1 > num2:
val = num1 * 10 + num2
else:
val = num2 * 10 + num1
res += freqs[val]
freqs[val] += 1
return res
558 - 2025-08-02 14:00:42 +0300 MSK
Print in Order
Links
Code
class Foo:
def __init__(self):
self._lock1 = threading.Lock()
self._lock2 = threading.Lock()
self._lock1.acquire()
self._lock2.acquire()
def first(self, printFirst: 'Callable[[], None]') -> None:
printFirst()
self._lock1.release()
def second(self, printSecond: 'Callable[[], None]') -> None:
with self._lock1:
printSecond()
self._lock2.release()
def third(self, printThird: 'Callable[[], None]') -> None:
with self._lock2:
printThird()
559 - 2025-08-02 13:55:22 +0300 MSK
Defanging an IP Address
Links
Code
class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]")
560 - 2025-08-02 13:54:26 +0300 MSK
Distribute Candies to People
Links
Code
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
res = [0] * num_people
i = 0
while candies > 0:
loss = min(i + 1, candies)
res[i % num_people] += loss
i += 1
candies -= loss
return res
561 - 2025-08-02 13:48:16 +0300 MSK
Distribute Candies to People
Links
Code
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
res = [0] * num_people
mult = 0
while candies > 0:
for i in range(num_people):
target = min((mult * num_people) + (i + 1), candies)
if candies > 0:
res[i] += target
candies -= target
else:
break
mult += 1
return res
562 - 2025-08-02 13:02:23 +0300 MSK
Duplicate Zeros
Links
Code
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
possible_dups = 0
length_ = len(arr) - 1
for left in range(length_ + 1):
if left > length_ - possible_dups:
break
if arr[left] == 0:
if left == length_ - possible_dups:
arr[length_] = 0
length_ -= 1
break
possible_dups += 1
last = length_ - possible_dups
for i in range(last, -1, -1):
if arr[i] == 0:
arr[i + possible_dups] = 0
possible_dups -= 1
arr[i + possible_dups] = 0
else:
arr[i + possible_dups] = arr[i]
563 - 2025-08-02 12:36:15 +0300 MSK
Duplicate Zeros
Links
Code
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
queue = deque()
for i in range(len(arr)):
num = arr[i]
if queue:
arr[i] = queue.popleft()
queue.append(num)
if num == 0:
queue.append(0)
564 - 2025-08-02 12:22:49 +0300 MSK
Sales Analysis III
Links
Code
SELECT
Product.product_id, Product.product_name
FROM
Sales
JOIN
Product
ON
Product.product_id = Sales.product_id
GROUP BY
Product.product_id, Product.product_name
HAVING
MIN(Sales.sale_date) >= '2019-01-01'
AND MAX(Sales.sale_date) <= '2019-03-31'
565 - 2025-08-02 11:12:11 +0300 MSK
Occurrences After Bigram
Links
Code
class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
words = text.split()
length = len(words)
if length < 3:
return []
res = []
i = 0
while i + 2 < length:
if words[i] == first and words[i+1] == second:
res.append(words[i+2])
i += 1
return res
566 - 2025-08-02 10:56:41 +0300 MSK
Project Employees I
Links
Code
SELECT
project_id,
ROUND(AVG(experience_years), 2) AS average_years
FROM
Project
JOIN
Employee
ON
Project.employee_id = Employee.employee_id
GROUP BY
project_id
567 - 2025-08-02 10:53:44 +0300 MSK
Project Employees I
Links
Code
SELECT
project_id,
ROUND(AVG(experience_years), 2) AS average_years
FROM
Project
JOIN
Employee
ON
Project.employee_id = Employee.employee_id
GROUP BY
project_id
568 - 2025-08-02 10:46:44 +0300 MSK
Product Sales Analysis I
Links
Code
SELECT
product_name, year, price
FROM
Sales
LEFT JOIN
Product
ON
Sales.product_id = Product.product_id
569 - 2025-08-02 10:41:17 +0300 MSK
Actors and Directors Who Cooperated At Least Three Times
Links
Code
SELECT
actor_id, director_id
FROM
ActorDirector
GROUP BY
actor_id, director_id
HAVING
COUNT(actor_id) >= 3;
570 - 2025-08-02 10:38:33 +0300 MSK
Remove All Adjacent Duplicates In String
Links
Code
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = []
for char in s:
if stack and char == stack[-1]:
stack.pop()
else:
stack.append(char)
return "".join(stack)
571 - 2025-08-02 10:31:09 +0300 MSK
Last Stone Weight
Links
Code
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
for i, num in enumerate(stones):
stones[i] = -num
heapq.heapify(stones)
while stones:
last = -heapq.heappop(stones)
if not stones:
return last
prev = -heapq.heappop(stones)
if last > prev:
heapq.heappush(stones, -(last - prev))
return 0
572 - 2025-08-02 10:28:21 +0300 MSK
Last Stone Weight
Links
Code
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones.sort()
while stones:
last = stones.pop()
if not stones:
return last
prev = stones[-1]
if last == prev:
stones.pop()
else:
stones[-1] = last - prev
stones.sort()
return 0
573 - 2025-08-02 09:19:39 +0300 MSK
Valid Boomerang
Links
Code
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
x1, y1 = points[0]
x2, y2 = points[1]
x3, y3 = points[2]
return (y2 - y1) * (x3 - x2) != (y3 - y2) * (x2 - x1)
574 - 2025-08-02 09:15:14 +0300 MSK
Matrix Cells in Distance Order
Links
Code
class Solution:
def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
res = []
for row in range(rows):
for col in range(cols):
res.append((row, col))
def key(point: tuple[int, int]) -> int:
row, col = point
return abs(row - rCenter) + abs(col - cCenter)
res.sort(key=key)
return res
575 - 2025-08-02 09:11:31 +0300 MSK
Matrix Cells in Distance Order
Links
Code
class Solution:
def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
res = []
for row in range(rows):
for col in range(cols):
dist = abs(row - rCenter) + abs(col - cCenter)
res.append((dist, row, col))
res.sort()
for i in range(len(res)):
res[i] = res[i][1:]
return res
576 - 2025-08-02 09:03:11 +0300 MSK
Divisor Game
Links
Code
class Solution:
def divisorGame(self, n: int) -> bool:
return n % 2 == 0
577 - 2025-08-02 08:55:10 +0300 MSK
Sum of Root To Leaf Binary Numbers
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
res = 0
queue = [(root, 0)]
while queue:
node, parent = queue.pop()
if node is None:
continue
val = (parent << 1) | node.val
if not node.left and not node.right:
res += val
queue.extend(((node.left, val), (node.right, val)))
return res
578 - 2025-08-02 08:53:28 +0300 MSK
Sum of Root To Leaf Binary Numbers
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
def dfs(node: Optional[TreeNode], parent: int) -> int:
if node is None:
return 0
cur_val = (parent << 1) | node.val
if not node.left and not node.right:
return cur_val
return dfs(node.left, cur_val) + dfs(node.right, cur_val)
return dfs(root, 0)
579 - 2025-08-02 08:48:51 +0300 MSK
Remove Outermost Parentheses
Links
Code
class Solution:
def removeOuterParentheses(self, s: str) -> str:
res = []
balance = 0
start = 0
for i, char in enumerate(s):
if char == '(':
balance += 1
else:
balance -= 1
if balance == 0:
res.append(s[start + 1:i])
start = i + 1
return "".join(res)
580 - 2025-08-02 08:38:26 +0300 MSK
Binary Prefix Divisible By 5
Links
Code
class Solution:
def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
cur = 0
for i in range(len(nums)):
cur <<= 1
cur |= nums[i]
nums[i] = cur % 5 == 0
return nums
581 - 2025-08-02 08:34:40 +0300 MSK
Partition Array Into Three Parts With Equal Sum
Links
Code
class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
total = sum(arr)
if total % 3 != 0:
return False
length = len(arr)
target = total // 3
cur = 0
count = 0
for i, num in enumerate(arr):
cur += num
if cur == target:
cur = 0
count += 1
if count == 2 and i + 1 < length:
return True
return False
582 - 2025-08-01 21:34:49 +0300 MSK
Complement of Base 10 Integer
Links
Code
class Solution:
def bitwiseComplement(self, n: int) -> int:
if n == 0:
return 1
res, count = 0, 0
while n > 0:
if n & 1 == 0:
res += 2 ** count
count += 1
n >>= 1
return res
583 - 2025-08-01 21:23:46 +0300 MSK
Maximize Sum Of Array After K Negations
Links
Code
class Solution:
def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
nums.sort()
for i in range(len(nums)):
num = nums[i]
if num < 0 and k > 0:
nums[i] = -num
k -= 1
else:
break
if k == 0 or k % 2 == 0:
return sum(nums)
nums.sort()
nums[0] = -nums[0]
return sum(nums)
584 - 2025-08-01 20:49:53 +0300 MSK
Available Captures for Rook
Links
Code
class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
bishop_row, bishop_col = -1, -1
length = len(board)
delta = (
(0, 1), (0, -1), (1, 0), (-1, 0)
)
for row in range(length):
for col in range(length):
if board[row][col] == "R":
bishop_row, bishop_col = row, col
break
if bishop_row != -1:
break
count = 0
for delta_row, delta_col in delta:
row, col = bishop_row, bishop_col
while 0 <= row < length and 0 <= col < length:
char = board[row][col]
if char == "p":
count += 1
break
elif char == "B":
break
row, col = row + delta_row, col + delta_col
return count
585 - 2025-08-01 20:14:01 +0300 MSK
Cousins in Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
def dfs(node: Optional[TreeNode], depth: int) -> tuple[int, int]:
if node is None:
return 0, 0
if node.val == x:
return depth, 0
if node.val == y:
return 0, depth
depth1_x, depth1_y = dfs(node.left, depth + 1)
depth2_x, depth2_y = dfs(node.right, depth + 1)
depth1, depth2 = depth1_x or depth2_x, depth1_y or depth2_y
if depth1 and depth2 and depth1 == depth + 1:
return 0, 0
return depth1, depth2
depth1, depth2 = dfs(root, 0)
return depth1 == depth2 and depth1 > 1
586 - 2025-08-01 19:32:18 +0300 MSK
Univalued Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
queue = [root]
while queue:
node = queue.pop()
if node.right and node.val != node.right.val:
return False
if node.left and node.val != node.left.val:
return False
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return True
587 - 2025-08-01 19:30:30 +0300 MSK
Univalued Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
def dfs(node: Optional[TreeNode]) -> bool:
if node is None:
return True
if node.left and node.val != node.left.val:
return False
if node.right and node.val != node.right.val:
return False
return dfs(node.left) and dfs(node.right)
return dfs(root)
588 - 2025-08-01 19:27:17 +0300 MSK
N-Repeated Element in Size 2N Array
Links
Code
class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
length = len(nums)
for k in range(1, 4):
for i in range(length - k):
if nums[i] == nums[i+k]:
return nums[i]
raise Exception
589 - 2025-08-01 19:18:48 +0300 MSK
N-Repeated Element in Size 2N Array
Links
Code
class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
enc = set()
for num in nums:
if num in enc:
return num
enc.add(num)
raise Exception
590 - 2025-08-01 19:16:55 +0300 MSK
Verifying an Alien Dictionary
Links
Code
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
pos = {}
for i, char in enumerate(order):
pos[char] = i
for i in range(len(words) - 1):
cur, nxt = words[i], words[i + 1]
cur_length, nxt_length = len(cur), len(nxt)
for j in range(cur_length):
if j >= nxt_length:
return False
cur_char, nxt_char = cur[j], nxt[j]
if cur_char == nxt_char:
continue
if pos[cur_char] > pos[nxt_char]:
return False
break
return True
591 - 2025-08-01 17:46:26 +0300 MSK
Delete Columns to Make Sorted
Links
Code
class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
res = 0
for col in range(len(strs[0])):
prev = 0
for row in range(len(strs)):
char = ord(strs[row][col])
if char >= prev:
prev = char
else:
res += 1
break
return res
592 - 2025-08-01 17:40:59 +0300 MSK
DI String Match
Links
Code
class Solution:
def diStringMatch(self, s: str) -> List[int]:
length = len(s)
res = [None] * (length + 1)
num_i, num_d = 0, length
for i, char in enumerate(s):
if char == "I":
res[i] = num_i
num_i += 1
else:
res[i] = num_d
num_d -= 1
res[-1] = num_i
return res
593 - 2025-08-01 17:39:13 +0300 MSK
DI String Match
Links
Code
class Solution:
def diStringMatch(self, s: str) -> List[int]:
length = len(s)
res = [None] * (length + 1)
num_i, num_d = 0, length
for i, char in enumerate(s):
is_i = char == "I"
if is_i:
res[i] = num_i
num_i += 1
else:
res[i] = num_d
num_d -= 1
if i != length - 1:
continue
if is_i:
res[i+1] = num_d
else:
res[i+1] = num_i
return res
594 - 2025-08-01 17:12:58 +0300 MSK
Valid Mountain Array
Links
Code
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
length = len(arr)
if length < 3:
return False
enc_peak = False
prev = arr[0]
for i, num in enumerate(arr[1:], 1):
if num == prev:
return False
if not enc_peak and num < prev:
enc_peak = True
if enc_peak and (num > prev or i == 1):
return False
prev = num
return enc_peak
595 - 2025-08-01 16:57:25 +0300 MSK
Unique Email Addresses
Links
Code
class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
enc = set()
for email in emails:
name, domain = email.rsplit("@", 1)
name = name.split("+", 1)[0].replace(".", "")
enc.add("@".join((name, domain)))
return len(enc)
596 - 2025-08-01 16:53:59 +0300 MSK
Long Pressed Name
Links
Code
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
name_i, typed_i = 0, 0
name_length, typed_length = len(name), len(typed)
while name_i < name_length and typed_i < typed_length:
if name[name_i] == typed[typed_i]:
name_i += 1
typed_i += 1
elif typed_i >= 1 and typed[typed_i] == typed[typed_i - 1]:
typed_i += 1
else:
return False
if name_i != name_length:
return False
while typed_i < typed_length:
if typed[typed_i] != typed[typed_i - 1]:
return False
typed_i += 1
return True
597 - 2025-08-01 16:43:05 +0300 MSK
Sort Array By Parity II
Links
Code
class Solution:
def sortArrayByParityII(self, nums: List[int]) -> List[int]:
res = [None] * len(nums)
i1, i2 = 0, 1
for num in nums:
if num % 2 == 0:
res[i1] = num
i1 += 2
else:
res[i2] = num
i2 += 2
return res
598 - 2025-08-01 16:39:51 +0300 MSK
Sort Array By Parity II
Links
Code
class Solution:
def sortArrayByParityII(self, nums: List[int]) -> List[int]:
stack_even, stack_odd = [], []
for num in nums:
if num % 2 == 0:
stack_even.append(num)
else:
stack_odd.append(num)
for i in range(len(nums)):
if i % 2 == 0:
nums[i] = stack_even.pop()
else:
nums[i] = stack_odd.pop()
return nums
599 - 2025-08-01 16:33:40 +0300 MSK
Reverse Only Letters
Links
Code
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
i, j = 0, len(s) - 1
res = [None] * len(s)
while i <= j:
char1, char2 = s[i], s[j]
if not char1.isalpha():
res[i] = char1
i += 1
elif not char2.isalpha():
res[j] = char2
j -= 1
else:
res[i], res[j] = char2, char1
i += 1
j -= 1
return "".join(res)
600 - 2025-08-01 16:24:11 +0300 MSK
X of a Kind in a Deck of Cards
Links
Code
import math
import functools
class Solution:
def hasGroupsSizeX(self, deck: List[int]) -> bool:
freqs = collections.defaultdict(int)
for num in deck:
freqs[num] += 1
gcd = functools.reduce(math.gcd, freqs.values())
return gcd > 1
601 - 2025-08-01 16:02:30 +0300 MSK
Smallest Range I
Links
Code
class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
min_num, max_num = min(nums), max(nums)
diff = max_num - min_num
res = max(diff - 2 * k, 0)
return res
602 - 2025-08-01 16:01:56 +0300 MSK
Smallest Range I
Links
Code
class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
min_num, max_num = float("inf"), float("-inf")
for num in nums:
if num > max_num:
max_num = num
if num < min_num:
min_num = num
diff = max_num - min_num
res = max(diff - 2 * k, 0)
return res
603 - 2025-08-01 15:50:58 +0300 MSK
Increasing Order Search Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def increasingBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
def dfs(node: TreeNode) -> tuple[TreeNode, TreeNode]:
if node.left:
root, tail = dfs(node.left)
tail.right = node
tail = node
node.left = None
else:
root, tail = node, node
if node.right:
right_root, right_tail = dfs(node.right)
tail.right = right_root
tail = right_tail
return root, tail
root, tail = dfs(root)
return root
604 - 2025-08-01 15:30:00 +0300 MSK
Surface Area of 3D Shapes
Links
Code
class Solution:
def surfaceArea(self, grid: list[list[int]]) -> int:
length = len(grid)
res = 0
adj_delta = (
(-1, 0), (1, 0), (0, -1), (0, 1)
)
for row in range(length):
for col in range(length):
height = grid[row][col]
if height == 0:
continue
res += 2
for row_delta, col_delta in adj_delta:
adj_row, adj_col = row + row_delta, col + col_delta
if 0 <= adj_row < length and 0 <= adj_col < length:
adj_height = grid[adj_row][adj_col]
else:
adj_height = 0
if height > adj_height:
res += grid[row][col] - adj_height
return res
605 - 2025-08-01 14:50:20 +0300 MSK
Fair Candy Swap
Links
Code
class Solution:
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
count1, count2 = sum(aliceSizes), sum(bobSizes)
delta = (count2 - count1) // 2
set2 = set(bobSizes)
for ex1 in aliceSizes:
ex2 = ex1 + delta
if ex2 in set2:
return ex1, ex2
raise Exception
606 - 2025-08-01 13:28:24 +0300 MSK
Uncommon Words from Two Sentences
Links
Code
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
freqs = collections.defaultdict(int)
res = []
for word in s1.split():
freqs[word] += 1
for word in s2.split():
freqs[word] += 1
for word, freq in freqs.items():
if freq == 1:
res.append(word)
return res
607 - 2025-08-01 13:24:00 +0300 MSK
Uncommon Words from Two Sentences
Links
Code
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
freqs1, freqs2 = defaultdict(int), defaultdict(int)
words1, words2 = s1.split(" "), s2.split(" ")
for word in words1:
freqs1[word] += 1
for word in words2:
freqs2[word] += 1
res = []
for word, freq in freqs1.items():
if freq != 1 or word in freqs2:
continue
res.append(word)
for word, freq in freqs2.items():
if freq != 1 or word in freqs1:
continue
res.append(word)
return res
608 - 2025-08-01 13:12:38 +0300 MSK
Projection Area of 3D Shapes
Links
Code
class Solution:
def projectionArea(self, grid: list[list[int]]) -> int:
res = 0
length = len(grid)
for i in range(length):
best_row = 0
best_col = 0
for j in range(length):
if grid[i][j]:
res += 1
best_row = max(best_row, grid[i][j])
best_col = max(best_col, grid[j][i])
res += best_row + best_col
return res
609 - 2025-08-01 09:59:43 +0300 MSK
Lemonade Change
Links
Code
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
change_5, change_10 = 0, 0
for bill in bills:
if bill == 5:
change_5 += 1
elif bill == 10 and change_5 > 0:
change_5 -= 1
change_10 += 1
elif bill == 10 and change_5 <= 0:
return False
elif bill == 20 and change_10 > 0 and change_5 > 0:
change_10 -= 1
change_5 -= 1
elif bill == 20 and change_5 >= 3:
change_5 -= 3
else:
return False
return True
610 - 2025-08-01 09:40:56 +0300 MSK
Rectangle Overlap
Links
Code
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
def intersect(p_left: int, p_right: int, q_left: int, q_right: int) -> bool:
return min(p_right, q_right) > max(p_left, q_left)
return (
intersect(rec1[0], rec1[2], rec2[0], rec2[2]) # width > 0
and intersect(rec1[1], rec1[3], rec2[1], rec2[3]) # height > 0
)
611 - 2025-08-01 08:25:54 +0300 MSK
Flipping an Image
Links
Code
class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for row in image:
row.reverse()
for i in range(len(row)):
row[i] ^= 1
return image
612 - 2025-08-01 08:21:20 +0300 MSK
Flipping an Image
Links
Code
class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for row in image:
row.reverse()
for i in range(len(row)):
if row[i] == 0:
row[i] = 1
else:
row[i] = 0
return image
613 - 2025-08-01 08:13:47 +0300 MSK
Positions of Large Groups
Links
Code
class Solution:
def largeGroupPositions(self, s: str) -> List[List[int]]:
res = []
start = 0
prev = s[0]
for i, char in enumerate(itertools.chain(s[1:], " "), 1):
if char == prev:
continue
if i - 1 - start >= 2:
res.append((start, i - 1))
start = i
prev = char
return res
614 - 2025-08-01 07:59:37 +0300 MSK
Goat Latin
Links
Code
class Solution:
def toGoatLatin(self, sentence: str) -> str:
cur_word = []
res = []
i = 0
for char in itertools.chain(sentence, " "):
if char != " ":
cur_word.append(char)
continue
if not cur_word:
continue
i += 1
if cur_word[0].lower() in ("a", "e", "i", "o", "u"):
cur_word.append("ma")
else:
cur_word.append(cur_word[0])
cur_word.append("ma")
cur_word[0] = ""
cur_word.append("a" * i)
res.append("".join(cur_word))
cur_word.clear()
return " ".join(res)
615 - 2025-08-01 07:51:03 +0300 MSK
Shortest Distance to a Character
Links
Code
class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
indexes = []
for i, char in enumerate(s):
if char == c:
indexes.append(i)
length = len(indexes)
res = []
i = 0
max_diff = float("inf")
for j, char in enumerate(s):
diff1 = abs(indexes[i] - j)
if i + 1 >= length:
diff2 = max_diff
else:
diff2 = abs(indexes[i + 1] - j)
if diff1 <= diff2:
res.append(diff1)
else:
res.append(diff2)
i += 1
return res
616 - 2025-08-01 07:33:33 +0300 MSK
Most Common Word
Links
Code
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
freqs = defaultdict(int)
banned_set = set(banned)
cur_word = []
for char in itertools.chain(paragraph, "."):
if char.isalpha():
cur_word.append(char.lower())
continue
if not cur_word:
continue
word = "".join(cur_word)
if word not in banned_set:
freqs[word] += 1
cur_word.clear()
most_freq = ""
most_freq_freq = 0
for word, freq in freqs.items():
if freq > most_freq_freq:
most_freq, most_freq_freq = word, freq
return most_freq
617 - 2025-08-01 07:15:40 +0300 MSK
Pascal’s Triangle
Links
Code
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
res = [(1, )]
cur_row = []
for row in range(1, numRows):
cur_row.append(1)
prev_row = res[-1]
for i in range(1, row):
cur_row.append(prev_row[i] + prev_row[i - 1])
cur_row.append(1)
res.append(tuple(cur_row))
cur_row.clear()
return res
618 - 2025-07-31 21:28:35 +0300 MSK
Largest Triangle Area
Links
Code
class Solution:
def largestTriangleArea(self, points: list[int]) -> float:
def area(p: tuple[int, int], q: tuple[int, int], r: tuple[int, int]) -> float:
return 0.5 * abs(
(p[0] * q[1])
+ (q[0] * r[1])
+ (r[0] * p[1])
- (p[1] * q[0])
- (q[1] * r[0])
- (r[1] * p[0])
)
res = max(
area(p, q, r)
for p, q, r in itertools.combinations(points, 3)
)
return res
619 - 2025-07-31 18:46:45 +0300 MSK
Number of Lines To Write String
Links
Code
class Solution:
def numberOfLines(self, widths: List[int], s: str) -> List[int]:
line_count = 1
line_width = 0
for char in s:
char_width = widths[ord(char) - 97]
line_width += char_width
if line_width > 100:
line_width = char_width
line_count += 1
return line_count, line_width
620 - 2025-07-31 18:31:00 +0300 MSK
Unique Morse Code Words
Links
Code
MORSE = (".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..")
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
enc = set()
for word in words:
enc.add("".join(MORSE[ord(char) - 97] for char in word))
return len(enc)
621 - 2025-07-31 18:29:59 +0300 MSK
Unique Morse Code Words
Links
Code
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
enc = set()
cur_morse = []
for word in words:
cur_morse.clear()
for char in word:
cur_morse.append(morse[ord(char) - 97])
enc.add("".join(cur_morse))
return len(enc)
622 - 2025-07-31 18:14:30 +0300 MSK
Rotate String
Links
Code
class Solution:
def rotateString(self, s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
return goal in "".join((s, s))
623 - 2025-07-31 17:53:16 +0300 MSK
Minimum Distance Between BST Nodes
Links
Code
class Solution:
def minDiffInBST(self, root: TreeNode) -> int:
self.ans = float('inf')
self.pred = None
self.inorder(root)
return self.ans
def inorder(self, root: TreeNode) -> None:
if root is None:
return
self.inorder(root.left)
if self.pred is not None:
self.ans = min(self.ans, root.val - self.pred)
self.pred = root.val
self.inorder(root.right)
624 - 2025-07-31 17:18:00 +0300 MSK
Jewels and Stones
Links
Code
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
jewels_set = set(jewels)
count = 0
for char in stones:
if char in jewels:
count += 1
return count
625 - 2025-07-31 17:16:38 +0300 MSK
Toeplitz Matrix
Links
Code
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i-1][j-1] != matrix[i][j]:
return False
return True
626 - 2025-07-31 17:05:37 +0300 MSK
Shortest Completing Word
Links
Code
class Solution:
def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
freq = defaultdict(int)
for char in licensePlate:
if char == " " or char.isnumeric():
continue
freq[char.lower()] += 1
cur_freq = {}
shortest = None
for word in words:
cur_freq.clear()
cur_freq.update(freq)
for char in word:
if not cur_freq:
break
if char not in cur_freq:
continue
new_freq = cur_freq[char] - 1
if new_freq <= 0:
cur_freq.pop(char)
else:
cur_freq[char] = new_freq
if not cur_freq and (shortest is None or len(word) < len(shortest)):
shortest = word
return shortest
627 - 2025-07-31 14:35:36 +0300 MSK
Largest Number At Least Twice of Others
Links
Code
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
largest1, largest2 = -1, -1
largest_i = -1
for i, num in enumerate(nums):
if num == largest2 or num == largest1:
continue
if num > largest2:
largest1 = largest2
largest2 = num
largest_i = i
elif num > largest1:
largest1 = num
if largest1 * 2 <= largest2:
return largest_i
return -1
628 - 2025-07-31 13:54:58 +0300 MSK
Flood Fill
Links
Code
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
target_color = image[sr][sc]
if target_color == color:
return image
length_row = len(image)
length_col = len(image[0])
dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
queue = [(sr, sc)]
while queue:
row, col = queue.pop()
if row < 0 or row >= length_row:
continue
if col < 0 or col >= length_col:
continue
if image[row][col] != target_color:
continue
image[row][col] = color
for row_delta, col_delta in dirs:
queue.append((row + row_delta, col + col_delta))
return image
629 - 2025-07-31 13:46:42 +0300 MSK
Flood Fill
Links
Code
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
target_color = image[sr][sc]
enc = set()
length_row = len(image)
length_col = len(image[0])
dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
queue = [(sr, sc)]
while queue:
row, col = queue.pop()
if row < 0 or row >= length_row:
continue
if col < 0 or col >= length_col:
continue
if (row, col) in enc:
continue
if image[row][col] != target_color:
continue
image[row][col] = color
enc.add((row, col))
for row_delta, col_delta in dirs:
queue.append((row + row_delta, col + col_delta))
return image
630 - 2025-07-31 13:03:46 +0300 MSK
Self Dividing Numbers
Links
Code
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
def self_dividing(num: int) -> bool:
if num == 0:
return False
cur_num = num
while cur_num > 0:
mod = cur_num % 10
cur_num //= 10
if mod == 0 or num % mod > 0:
return False
return True
ans = []
for n in range(left, right + 1):
if self_dividing(n):
ans.append(n)
return ans
631 - 2025-07-31 11:07:49 +0300 MSK
Degree of an Array
Links
Code
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
left, right, freq = defaultdict(int), defaultdict(int), defaultdict(int)
max_freq = 0
for i, num in enumerate(nums):
if num not in left:
left[num] = i
right[num] = i
freq[num] += 1
max_freq = max(max_freq, freq[num])
min_length = len(nums)
for num, num_freq in freq.items():
if num_freq != max_freq:
continue
min_length = min(min_length, right[num] - left[num] + 1)
return min_length
632 - 2025-07-31 11:00:20 +0300 MSK
Count Binary Substrings
Links
Code
class Solution:
def countBinarySubstrings(self, s: str) -> int:
groups = [1]
for i in range(1, len(s)):
if s[i-1] != s[i]:
groups.append(1)
else:
groups[-1] += 1
ans = 0
for i in range(1, len(groups)):
ans += min(groups[i-1], groups[i])
return ans
633 - 2025-07-31 10:28:31 +0300 MSK
Baseball Game
Links
Code
class Solution:
def calPoints(self, operations: List[str]) -> int:
stack = []
stack_sum = 0
for op in operations:
if op.isnumeric() or op.startswith("-"):
new_score = int(op)
stack.append(new_score)
stack_sum += new_score
elif op == "+":
new_score = stack[-1] + stack[-2]
stack_sum += new_score
stack.append(new_score)
elif op == "D":
new_score = stack[-1] * 2
stack_sum += new_score
stack.append(new_score)
elif op == "C":
stack_sum -= stack[-1]
stack.pop()
else:
raise Exception(op)
return stack_sum
634 - 2025-07-31 10:04:49 +0300 MSK
Bitwise ORs of Subarrays
Links
Code
class Solution:
def subarrayBitwiseORs(self, arr: List[int]) -> int:
ors = set()
cur = {0}
for num in arr:
cur = {num | cur_num for cur_num in cur} | {num}
ors |= cur
return len(ors)
635 - 2025-07-30 22:05:38 +0300 MSK
Valid Palindrome II
Links
Code
class Solution:
def validPalindrome(self, s: str) -> bool:
def check(i: int, j: int) -> bool:
while i < j:
if s[i] != s[j]:
return False
i, j = i + 1, j - 1
return True
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return check(i + 1, j) or check(i, j - 1)
i, j = i + 1, j - 1
return True
636 - 2025-07-30 22:00:12 +0300 MSK
Longest Continuous Increasing Subsequence
Links
Code
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
prev = nums[0]
length = 1
max_length = 1
for num in nums[1:]:
if num > prev:
length += 1
else:
max_length = max(length, max_length)
length = 1
prev = num
return max(length, max_length)
637 - 2025-07-30 21:55:12 +0300 MSK
Second Minimum Node In a Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findSecondMinimumValue(self, root):
self.ans = float('inf')
min1 = root.val
def dfs(node):
if node:
if min1 < node.val < self.ans:
self.ans = node.val
elif node.val == min1:
dfs(node.left)
dfs(node.right)
dfs(root)
return self.ans if self.ans < float('inf') else -1
638 - 2025-07-30 21:02:37 +0300 MSK
Robot Return to Origin
Links
Code
class Solution:
def judgeCircle(self, moves: str) -> bool:
row, col = 0, 0
coords = {
"R": (0, 1),
"L": (0, -1),
"U": (1, 0),
"D": (-1, 0)
}
for move in moves:
row_delta, col_delta = coords[move]
row += row_delta
col += col_delta
return row == 0 and col == 0
639 - 2025-07-30 20:59:49 +0300 MSK
Maximum Product of Three Numbers
Links
Code
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort()
pos_res = nums[-1] * nums[-2] * nums[-3]
if nums[0] >= 0:
return pos_res
neg_res = nums[0] * nums[1] * nums[-1]
return max(pos_res, neg_res)
640 - 2025-07-30 20:52:44 +0300 MSK
Swap Salary
Links
Code
UPDATE
Salary
SET
sex = (
CASE
WHEN
sex = 'f'
THEN
'm'
ELSE
'f'
END
);
641 - 2025-07-30 20:47:51 +0300 MSK
Not Boring Movies
Links
Code
SELECT
id, movie, description, rating
FROM
Cinema
WHERE
description != 'boring'
AND id % 2 != 0
ORDER BY
rating DESC;
642 - 2025-07-30 20:42:31 +0300 MSK
Biggest Single Number
Links
Code
WITH nums AS (
SELECT
num
FROM
MyNumbers
GROUP BY
num
HAVING
COUNT(num) = 1
)
SELECT
MAX(num) AS num
FROM
nums;
643 - 2025-07-30 20:35:12 +0300 MSK
Merge Two Binary Trees
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if root1 is None:
return root2
if root2 is None:
return root1
queue = [(root1, root2)]
while queue:
node1, node2 = queue.pop()
if node1 is None or node2 is None:
continue
node1.val += node2.val
if node1.left is None:
node1.left = node2.left
else:
queue.append((node1.left, node2.left))
if node1.right is None:
node1.right = node2.right
else:
queue.append((node1.right, node2.right))
return root1
644 - 2025-07-30 20:27:09 +0300 MSK
Merge Two Binary Trees
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(node1: Optional[TreeNode], node2: Optional[TreeNode]) -> None:
if node1 is None:
return node2
if node2 is None:
return node1
node1.val += node2.val
node1.left = dfs(node1.left, node2.left)
node1.right = dfs(node1.right, node2.right)
return node1
return dfs(root1, root2)
645 - 2025-07-30 20:12:39 +0300 MSK
Triangle Judgement
Links
Code
SELECT
x, y, z, (
CASE
WHEN
((x+y+z) - GREATEST(x,y,z)) > GREATEST(x,y,z)
THEN
'Yes'
ELSE
'No'
END
) AS triangle
FROM
Triangle;
646 - 2025-07-30 20:09:55 +0300 MSK
Triangle Judgement
Links
Code
(
SELECT
x, y, z, 'Yes' AS triangle
FROM
Triangle
WHERE
(x + y > z) AND (y + z > x) AND (z + x > y)
) UNION (
SELECT
x, y, z, 'No' AS triangle
FROM
Triangle
WHERE (x + y <= z) OR (y + z <= x) OR (z + x <= y)
);
647 - 2025-07-30 20:05:18 +0300 MSK
Sales Person
Links
Code
SELECT
sales_person.name
FROM (
Orders orders
JOIN
Company company
ON
orders.com_id = company.com_id
AND company.name = 'RED'
RIGHT JOIN
SalesPerson sales_person
ON
sales_person.sales_id = orders.sales_id
)
WHERE
orders.sales_id IS NULL;
648 - 2025-07-30 19:52:43 +0300 MSK
Minimum Index Sum of Two Lists
Links
Code
class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
indexes = {}
res = []
if len(list1) > len(list2):
first, second = list2, list1
else:
first, second = list1, list2
for i, string in enumerate(first):
indexes[string] = i
min_sum = float("inf")
res = []
for j, string in enumerate(second):
if string not in indexes:
continue
cur_sum = indexes[string] + j
if cur_sum < min_sum:
res.clear()
res.append(string)
min_sum = cur_sum
elif cur_sum == min_sum:
res.append(string)
return res
649 - 2025-07-30 19:27:05 +0300 MSK
Range Addition II
Links
Code
class Solution:
def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
min_row = m
min_col = n
for range_row, range_col in ops:
min_row = min(min_row, range_row)
min_col = min(min_col, range_col)
return min_row * min_col
650 - 2025-07-30 19:18:29 +0300 MSK
Classes With at Least 5 Students
Links
Code
SELECT
class
FROM
Courses
GROUP BY
class
HAVING
COUNT(class) >= 5;
651 - 2025-07-30 19:14:46 +0300 MSK
Big Countries
Links
Code
SELECT
World.name, World.population, World.area
FROM
World
WHERE
World.area >= 3000000
OR World.population >= 25000000;
652 - 2025-07-30 19:11:57 +0300 MSK
Longest Harmonious Subsequence
Links
Code
class Solution:
def findLHS(self, nums):
freq = defaultdict(int)
max_length = 0
for num in nums:
freq[num] += 1
for num in freq:
nxt = num + 1
if nxt not in freq:
continue
cur_length = freq[num] + freq[nxt]
max_length = max(max_length, cur_length)
return max_length
653 - 2025-07-30 18:59:58 +0300 MSK
N-ary Tree Postorder Traversal
Links
Code
"""
# Definition for a Node.
class Node:
def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
if root is None:
return []
res = []
queue = [root]
while queue:
node = queue.pop()
res.append(node.val)
for child in node.children:
queue.append(child)
res.reverse()
return res
654 - 2025-07-30 18:49:52 +0300 MSK
N-ary Tree Postorder Traversal
Links
Code
"""
# Definition for a Node.
class Node:
def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
res = []
def dfs(node: Node, res: list[int]) -> None:
if node is None:
return
for child in node.children:
dfs(child, res)
res.append(node.val)
dfs(root, res)
return res
655 - 2025-07-30 18:45:39 +0300 MSK
N-ary Tree Preorder Traversal
Links
Code
"""
# Definition for a Node.
class Node:
def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
self.val = val
self.children = children
"""
class Solution:
def preorder(self, root: 'Node') -> List[int]:
if root is None:
return []
res = []
queue = [root]
while queue:
node = queue.pop()
res.append(node.val)
queue.extend(reversed(node.children))
return res
656 - 2025-07-30 18:44:00 +0300 MSK
N-ary Tree Preorder Traversal
Links
Code
"""
# Definition for a Node.
class Node:
def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
self.val = val
self.children = children
"""
class Solution:
def preorder(self, root: 'Node') -> List[int]:
if root is None:
return []
res = []
queue = deque((root, ))
while queue:
node = queue.popleft()
res.append(node.val)
queue.extendleft(reversed(node.children))
return res
657 - 2025-07-30 18:35:45 +0300 MSK
N-ary Tree Preorder Traversal
Links
Code
"""
# Definition for a Node.
class Node:
def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
self.val = val
self.children = children
"""
class Solution:
def preorder(self, root: 'Node') -> List[int]:
res = []
def dfs(node: Optional[Node], res: list[int]) -> None:
if node is None:
return
res.append(node.val)
for child in node.children:
dfs(child, res)
dfs(root, res)
return res
658 - 2025-07-30 18:32:15 +0300 MSK
Customer Placing the Largest Number of Orders
Links
Code
SELECT
Orders.customer_number
FROM
Orders
GROUP BY
Orders.customer_number
ORDER BY
COUNT(Orders.customer_number) DESC
LIMIT
1;
659 - 2025-07-30 18:31:28 +0300 MSK
Customer Placing the Largest Number of Orders
Links
Code
SELECT
Orders.customer_number
FROM
Orders
GROUP BY
Orders.customer_number
ORDER BY
COUNT(*) DESC
LIMIT
1;
660 - 2025-07-30 18:25:43 +0300 MSK
Find Customer Referee
Links
Code
SELECT
Customer.name
FROM
Customer
WHERE
Customer.referee_id != 2
OR Customer.referee_id IS NULL
661 - 2025-07-30 18:19:10 +0300 MSK
Employee Bonus
Links
Code
SELECT
Employee.name, Bonus.bonus
FROM
Employee
LEFT JOIN
Bonus
ON
Employee.empId = Bonus.empId
WHERE
Bonus.bonus IS NULL
OR Bonus.bonus < 1000
662 - 2025-07-30 18:07:19 +0300 MSK
Distribute Candies
Links
Code
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
types = set()
max_length = len(candyType) // 2
for candy in candyType:
types.add(candy)
if len(types) >= max_length:
return max_length
return len(types)
663 - 2025-07-30 17:54:50 +0300 MSK
Subtree of Another Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
def dfs(node: Optional[TreeNode], sub_node: Optional[TreeNode]) -> bool:
if not node and not sub_node:
return True
if not node or not sub_node:
return False
if node.val != sub_node.val:
return False
return dfs(node.left, sub_node.left) and dfs(node.right, sub_node.right)
def dfs2(node: Optional[TreeNode], sub_node: Optional[TreeNode]) -> bool:
if dfs(node, sub_node):
return True
if not node or not sub_node:
return False
return dfs2(node.left, sub_node) or dfs2(node.right, sub_node)
return dfs2(root, subRoot)
664 - 2025-07-30 17:36:45 +0300 MSK
Reshape the Matrix
Links
Code
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
if len(mat) * len(mat[0]) != r * c:
return mat
new_mat = [[None] * c for _ in range(r)]
new_row = 0
new_col = 0
for row in mat:
for col in row:
if new_col == c:
new_col = 0
new_row += 1
new_mat[new_row][new_col] = col
new_col += 1
return new_mat
665 - 2025-07-30 16:27:11 +0300 MSK
Binary Tree Tilt
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTilt(self, root: Optional[TreeNode]) -> int:
def dfs(node: Optional[TreeNode]) -> tuple[int, int]:
if node is None:
return 0, 0
left_sum, left_tilt = dfs(node.left)
right_sum, right_tilt = dfs(node.right)
tilt_sum = left_tilt + right_tilt + abs(left_sum - right_sum)
node_sum = node.val + left_sum + right_sum
return node_sum, tilt_sum
_, tilt_sum = dfs(root)
return tilt_sum
666 - 2025-07-30 16:07:35 +0300 MSK
Array Partition
Links
Code
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
length = len(nums)
i = 0
sum = 0
while i < length:
sum += nums[i]
i += 2
return sum
667 - 2025-07-30 16:04:16 +0300 MSK
Maximum Depth of N-ary Tree
Links
Code
"""
# Definition for a Node.
class Node:
def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if root is None:
return 0
queue: deque[tuple[Node, int]] = deque(((root, 1),))
max_depth = 0
while queue:
node, depth = queue.popleft()
max_depth = depth
for child in node.children:
queue.append((child, 1 + depth))
return max_depth
668 - 2025-07-30 15:53:02 +0300 MSK
Maximum Depth of N-ary Tree
Links
Code
"""
# Definition for a Node.
class Node:
def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
def dfs(node: Node) -> int:
if not node:
return 0
if not node.children:
return 1
return 1 + max(dfs(child) for child in node.children)
return dfs(root)
669 - 2025-07-30 15:50:06 +0300 MSK
Student Attendance Record I
Links
Code
class Solution:
def checkRecord(self, s: str) -> bool:
a_count = 0
l_count = 0
for char in s:
if char == "P":
l_count = 0
elif char == "A":
a_count += 1
l_count = 0
elif char == "L":
l_count += 1
if l_count >= 3 or a_count >= 2:
return False
return True
670 - 2025-07-30 15:40:51 +0300 MSK
Reverse String II
Links
Code
class Solution:
def reverseStr(self, s: str, k: int) -> str:
length = len(s)
if length == 1:
return s
if length <= k:
return s[::-1]
res = []
i = 0
while i < length:
new_i = i + 2 * k
res.append(s[i+k-1:i:-1])
res.append(s[i])
res.append(s[i+k:new_i])
i = new_i
return "".join(res)
671 - 2025-07-30 15:11:27 +0300 MSK
Longest Uncommon Subsequence I
Links
Code
class Solution:
def findLUSlength(self, a: str, b: str) -> int:
if a == b:
return -1
else:
return max(len(a), len(b))
672 - 2025-07-30 15:08:16 +0300 MSK
Longest Subarray With Maximum Bitwise AND
Links
Code
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
max_val = ans = current_streak = 0
for num in nums:
if max_val < num:
max_val = num
ans = current_streak = 0
if max_val == num:
current_streak += 1
else:
current_streak = 0
ans = max(ans, current_streak)
return ans
673 - 2025-07-30 15:06:29 +0300 MSK
Longest Subarray With Maximum Bitwise AND
Links
Code
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
max_and = max(nums)
max_length = 0
cur_length = 0
for num in nums:
if num == max_and:
cur_length += 1
else:
max_length = max(max_length, cur_length)
cur_length = 0
return max(max_length, cur_length)
674 - 2025-07-30 14:49:28 +0300 MSK
Detect Capital
Links
Code
class Solution:
def detectCapitalUse(self, word: str) -> bool:
length = len(word)
if length == 1:
return True
def is_cap(char: str) -> bool:
res = 65 <= ord(char) <= 90
return res
first_cap, second_cap = is_cap(word[0]), is_cap(word[1])
if first_cap and second_cap:
should_be_cap = True
elif first_cap and not second_cap:
should_be_cap = False
elif not first_cap and second_cap:
return False
elif not first_cap and not second_cap:
should_be_cap = False
else:
raise Exception
for char in word[2:]:
if is_cap(char) != should_be_cap:
return False
return True
675 - 2025-07-29 21:27:41 +0300 MSK
Game Play Analysis I
Links
Code
SELECT
player_id, MIN(event_date) as "first_login"
FROM
Activity
GROUP BY
player_id
676 - 2025-07-29 21:05:02 +0300 MSK
Perfect Number
Links
Code
class Solution:
def checkPerfectNumber(self, num: int) -> bool:
if num == 1:
return False
count = 1
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
count += i + (num // i)
return num == count
677 - 2025-07-29 20:50:01 +0300 MSK
Base 7
Links
Code
class Solution:
def convertToBase7(self, num: int) -> str:
if num > -7 and num < 7:
return str(num)
res_arr = []
sign = ""
if num < 0:
sign = "-"
num = -num
while num:
res_arr.append(str(num % 7))
num //= 7
res = sign + "".join(reversed(res_arr))
return res
678 - 2025-07-29 20:45:22 +0300 MSK
Next Greater Element I
Links
Code
class Solution:
def nextGreaterElement(self, nums1: list[int], nums2: list[int]) -> list[int]:
stack = []
greater = {}
for num in nums2:
while stack and num > stack[-1]:
greater[stack.pop()] = num
stack.append(num)
for num in stack:
greater[num] = -1
return [greater[num] for num in nums1]
679 - 2025-07-29 19:17:54 +0300 MSK
Teemo Attacking
Links
Code
class Solution:
def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
total = 0
cur_end = -1
for second in timeSeries:
if second > cur_end:
total += duration
else:
total += duration - (cur_end - second) - 1
cur_end = second + duration - 1
return total
680 - 2025-07-29 18:55:38 +0300 MSK
Hamming Distance
Links
Code
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
count = 0
while x or y:
if x % 2 != y % 2:
count += 1
x //= 2
y //= 2
return count
681 - 2025-07-29 18:52:23 +0300 MSK
Number of Segments in a String
Links
Code
class Solution:
def countSegments(self, s: str) -> int:
length = len(s)
count = 0
is_segment = False
for char in s:
is_space = char == " "
if not is_segment and not is_space:
is_segment = True
count += 1
elif is_space:
is_segment = False
return count
682 - 2025-07-29 18:27:23 +0300 MSK
Convert a Number to Hexadecimal
Links
Code
class Solution:
def toHex(self, num: int) -> str:
if num >=0 and num < 10:
return str(num)
if num < 0:
num = (1 << 32) + num
symbols = "0123456789abcdef"
res = []
while num > 0:
mod = num % 16
res.append(symbols[mod])
num //= 16
return "".join(reversed(res))
683 - 2025-07-29 17:59:54 +0300 MSK
Binary Watch
Links
Code
class Solution:
def readBinaryWatch(self, num: int) -> list[str]:
times = []
for h in range(12):
for m in range(60):
hOnes = bin(h).count('1')
mOnes = bin(m).count('1')
if hOnes + mOnes == num:
times.append(f"{h}:{m:02d}")
return times
684 - 2025-07-29 17:38:44 +0300 MSK
Nim Game
Links
Code
class Solution:
def canWinNim(self, n: int) -> bool:
return n % 4 != 0
685 - 2025-07-29 17:38:31 +0300 MSK
Nim Game
Links
Code
class Solution:
def canWinNim(self, n: int) -> bool:
if n < 3:
return True
True, True, True, False, True, True, True
1, 2, 3, 4, 5, 6, 7
return n % 4 != 0
686 - 2025-07-29 16:37:09 +0300 MSK
Delete Duplicate Emails
Links
Code
DELETE FROM
Person
WHERE
id NOT IN (
SELECT MIN(id) FROM Person
GROUP BY email
)
;
687 - 2025-07-29 16:11:49 +0300 MSK
Rising Temperature
Links
Code
SELECT
today.id
FROM
Weather today
CROSS JOIN
Weather yesterday
WHERE
(today.recordDate - yesterday.recordDate = 1)
AND today.temperature > yesterday.temperature
688 - 2025-07-29 13:59:48 +0300 MSK
Smallest Subarrays With Maximum Bitwise OR
Links
Code
class Solution:
def smallestSubarrays(self, nums: List[int]) -> List[int]:
n = len(nums)
pos = [-1] * 31
ans = [0] * n
for i in range(n - 1, -1, -1):
j = i
for bit in range(31):
if (nums[i] & (1 << bit)) == 0:
if pos[bit] != -1:
j = max(j, pos[bit])
else:
pos[bit] = i
ans[i] = j - i + 1
return ans
689 - 2025-07-28 20:06:14 +0300 MSK
Employees Earning More Than Their Managers
Links
Code
SELECT employee.name AS Employee
FROM Employee employee
JOIN Employee manager
ON employee.managerId = manager.id
WHERE employee.salary > manager.salary;
691 - 2025-07-28 16:53:12 +0300 MSK
Valid Phone Numbers
Links
Code
awk '
/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ { print $0 }
/^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$/ { print $0 }
' file.txt
692 - 2025-07-28 16:52:43 +0300 MSK
Valid Phone Numbers
Links
Code
cat file.txt | awk '
/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ { print $0 }
/^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$/ { print $0 }
'
693 - 2025-07-28 16:45:20 +0300 MSK
Customers Who Never Order
Links
Code
SELECT name as "Customers"
FROM Customers
WHERE id NOT IN (
SELECT customerId
FROM Orders
);
694 - 2025-07-28 16:35:55 +0300 MSK
Duplicate Emails
Links
Code
SELECT email FROM Person
GROUP BY email
HAVING COUNT(email) > 1;
695 - 2025-07-28 16:25:34 +0300 MSK
Count Number of Maximum Bitwise-OR Subsets
Links
Code
class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
max_or_value = 0
n = len(nums)
for num in nums:
max_or_value |= num
memo = [[-1] * (max_or_value + 1) for _ in range(n)]
return self._count_subsets_recursive(nums, 0, 0, max_or_value, memo)
def _count_subsets_recursive(
self,
nums: List[int],
index: int,
current_or: int,
target_or: int,
memo: List[List[int]],
) -> int:
if index == len(nums):
return 1 if current_or == target_or else 0
if memo[index][current_or] != -1:
return memo[index][current_or]
count_without = self._count_subsets_recursive(
nums, index + 1, current_or, target_or, memo
)
count_with = self._count_subsets_recursive(
nums, index + 1, current_or | nums[index], target_or, memo
)
res = count_without + count_with
memo[index][current_or] = res
return res
696 - 2025-07-27 19:03:38 +0300 MSK
Count Hills and Valleys in an Array
Links
Code
class Solution:
def countHillValley(self, nums: List[int]) -> int:
res = 0
length = len(nums)
for i in range(1, length - 1):
if nums[i] == nums[i - 1]:
continue
left = 0
for j in range(i - 1, -1, -1):
if nums[j] > nums[i]:
left = 1
break
elif nums[j] < nums[i]:
left = -1
break
right = 0
for j in range(i + 1, length):
if nums[j] > nums[i]:
right = 1
break
elif nums[j] < nums[i]:
right = -1
break
if left == right and left != 0:
res += 1
return res
697 - 2025-07-26 18:50:49 +0300 MSK
Maximize Subarrays After Removing One Conflicting Pair
Links
Code
class Solution:
def maxSubarrays(self, n: int, conflictingPairs: List[List[int]]) -> int:
bMin1 = [2**31 - 1] * (n + 1)
bMin2 = [2**31 - 1] * (n + 1)
for pair in conflictingPairs:
a = min(pair[0], pair[1])
b = max(pair[0], pair[1])
if bMin1[a] > b:
bMin2[a] = bMin1[a]
bMin1[a] = b
elif bMin2[a] > b:
bMin2[a] = b
res = 0
ib1 = n
b2 = 0x3FFFFFFF
delCount = [0] * (n + 1)
for i in range(n, 0, -1):
if bMin1[ib1] > bMin1[i]:
b2 = min(b2, bMin1[ib1])
ib1 = i
else:
b2 = min(b2, bMin1[i])
res += min(bMin1[ib1], n + 1) - i
delCount[ib1] += min(min(b2, bMin2[ib1]), n + 1) - min(
bMin1[ib1], n + 1
)
return res + max(delCount)
698 - 2025-07-26 18:48:20 +0300 MSK
Ugly Number
Links
Code
class Solution(object):
def isUgly(self, n):
if n <= 0:
return False
while n % 2 == 0:
n //= 2
while n % 3 == 0:
n //= 3
while n % 5 == 0:
n //= 5
return n == 1
699 - 2025-07-25 13:23:28 +0300 MSK
1-bit and 2-bit Characters
Links
Code
class Solution(object):
def isOneBitCharacter(self, bits):
i = 0
while i < len(bits) - 1:
i += bits[i] + 1
return i == len(bits) - 1
700 - 2025-07-25 13:15:13 +0300 MSK
To Lower Case
Links
Code
class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower()
701 - 2025-07-25 13:14:11 +0300 MSK
Kth Largest Element in a Stream
Links
Code
class KthLargest:
def __init__(self, k: int, nums: List[int]):
if len(nums) < k:
nums.extend((float("-inf"),) * (k - len(nums)))
nums.sort()
self._nums: list[int] = nums[-k:]
self._k: int = k
def add(self, val: int) -> int:
if val > self._nums[0]:
self._nums[0] = val
self._nums.sort()
return self._nums[-self._k]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
702 - 2025-07-25 12:37:39 +0300 MSK
Number of Students Doing Homework at a Given Time
Links
Code
class Solution:
def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
count = 0
for start, end in zip(startTime, endTime):
if queryTime >= start and queryTime <= end:
count += 1
return count
703 - 2025-07-25 12:29:53 +0300 MSK
Count Negative Numbers in a Sorted Matrix
Links
Code
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
count = 0
for i, row in enumerate(grid):
for j, num in enumerate(row):
if num < 0:
count += len(row) - j
break
return count
704 - 2025-07-25 12:18:12 +0300 MSK
Combine Two Tables
Links
Code
SELECT firstName, lastName, city, state
FROM Person LEFT JOIN Address
ON Person.personId = Address.personId
705 - 2025-07-25 12:07:53 +0300 MSK
Delete Characters to Make Fancy String
Links
Code
class Solution:
def makeFancyString(self, s: str) -> str:
length = len(s)
if length < 3:
return s
prev_char, prev_char_count = "", 0
res = []
for char in s:
if char != prev_char:
prev_char = char
prev_char_count = 1
res.append(char)
elif prev_char_count < 2:
prev_char_count += 1
res.append(char)
return "".join(res)
706 - 2025-07-25 11:57:05 +0300 MSK
Maximum Erasure Value
Links
Code
class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
sub: deque[int] = deque()
sub_nums: set[int] = set()
cur_sum: int = 0
max_sum: int = 0
for num in nums:
while num in sub_nums:
sub_num = sub.popleft()
sub_nums.remove(sub_num)
cur_sum -= sub_num
sub.append(num)
sub_nums.add(num)
cur_sum += num
max_sum = max(cur_sum, max_sum)
return max_sum
707 - 2025-07-25 09:50:01 +0300 MSK
Maximum Unique Subarray Sum After Deletion
Links
Code
class Solution:
def maxSum(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
nums.sort()
if nums[-1] <= 0:
return nums[-1]
res = 0
if nums[0] > 0:
res = nums[0]
for i, num in enumerate(nums[1:], 1):
if num <= 0 or num == nums[i - 1]:
continue
res += num
return res
708 - 2025-07-24 18:52:24 +0300 MSK
Maximum Score From Removing Substrings
Links
Code
class Solution:
def maximumGain(self, s: str, x: int, y: int) -> int:
total_score = 0
high_priority_pair = "ab" if x > y else "ba"
low_priority_pair = "ba" if high_priority_pair == "ab" else "ab"
# First pass: remove high priority pair
string_after_first_pass = self.remove_substring(s, high_priority_pair)
removed_pairs_count = (len(s) - len(string_after_first_pass)) // 2
# Calculate score from first pass
total_score += removed_pairs_count * max(x, y)
# Second pass: remove low priority pair
string_after_second_pass = self.remove_substring(
string_after_first_pass, low_priority_pair
)
removed_pairs_count = (
len(string_after_first_pass) - len(string_after_second_pass)
) // 2
# Calculate score from second pass
total_score += removed_pairs_count * min(x, y)
return total_score
def remove_substring(self, input: str, target_pair: str) -> str:
char_stack = []
# Iterate through each character in the input string
for current_char in input:
# Check if current character forms the target pair with the top of the stack
if (
current_char == target_pair[1]
and char_stack
and char_stack[-1] == target_pair[0]
):
char_stack.pop() # Remove the matching character from the stack
else:
char_stack.append(current_char)
# Reconstruct the remaining string after removing target pairs
return "".join(char_stack)
709 - 2025-07-24 17:40:53 +0300 MSK
Minimum Score After Removals on a Tree
Links
Code
class Solution:
def calc(self, part1: int, part2: int, part3: int) -> int:
return max(part1, part2, part3) - min(part1, part2, part3)
def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:
length = len(nums)
parent_to_child: list[int] = [[] for _ in range(length)]
for node_1, node_2 in edges:
parent_to_child[node_1].append(node_2)
parent_to_child[node_2].append(node_1)
total = 0
for num in nums:
total ^= num
res = float("inf")
def dfs2(node: int, parent: int, oth: int, anc: int) -> int:
son = nums[node]
for child in parent_to_child[node]:
if child == parent:
continue
son ^= dfs2(child, node, oth, anc)
if parent == anc:
return son
nonlocal res
res = min(res, self.calc(oth, son, total ^ oth ^ son))
return son
def dfs(node: int, parent: int) -> int:
son = nums[node]
for child in parent_to_child[node]:
if child == parent:
continue
son ^= dfs(child, node)
for child in parent_to_child[node]:
if child == parent:
dfs2(child, node, son, node)
return son
dfs(0, -1)
return res
710 - 2025-07-20 16:53:28 +0300 MSK
Delete Duplicate Folders in System
Links
Code
class Trie:
serial: str = ""
children: dict[str, "Trie"]
def __init__(self) -> None:
self.children = dict()
class Solution:
def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:
root = Trie()
freq = Counter()
for path in paths:
cur = root
for node in path:
if node not in cur.children:
cur.children[node] = Trie()
cur = cur.children[node]
def construct(node: Trie) -> None:
if not node.children:
return
serial: list[str] = []
for folder, child in node.children.items():
construct(child)
serial.append(f"{folder}({child.serial})")
serial.sort()
node.serial = "".join(serial)
freq[node.serial] += 1
construct(root)
ans = list()
path = list()
def operate(node: Trie) -> None:
if freq[node.serial] > 1:
return
if path:
ans.append(path[:])
for folder, child in node.children.items():
path.append(folder)
operate(child)
path.pop()
operate(root)
return ans
711 - 2025-04-15 16:14:06 +0300 MSK
Count Good Triplets in an Array
Links
Code
from sortedcontainers import SortedList
from typing import List
class Solution:
def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:
index_map = {num: i for i, num in enumerate(nums2)}
indices = [index_map[num] for num in nums1]
left_counts = []
left_sorted = SortedList()
for idx in indices:
left_counts.append(left_sorted.bisect_left(idx))
left_sorted.add(idx)
right_counts = []
right_sorted = SortedList()
for idx in reversed(indices):
right_counts.append(len(right_sorted) - right_sorted.bisect_right(idx))
right_sorted.add(idx)
right_counts.reverse()
return sum(left * right for left, right in zip(left_counts, right_counts))
712 - 2025-04-14 19:45:07 +0300 MSK
Count Good Triplets
Links
Code
class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
ans = 0
n = len(arr)
total = [0] * 1001
for j in range(n):
for k in range(j + 1, n):
if abs(arr[j] - arr[k]) <= b:
lj, rj = arr[j] - a, arr[j] + a
lk, rk = arr[k] - c, arr[k] + c
l = max(0, lj, lk)
r = min(1000, rj, rk)
if l <= r:
ans += total[r] if l == 0 else total[r] - total[l - 1]
for k in range(arr[j], 1001):
total[k] += 1
return ans
713 - 2025-04-13 17:10:23 +0300 MSK
Count Good Numbers
Links
Code
class Solution:
def countGoodNumbers(self, n: int) -> int:
mod = 10**9 + 7
# use fast exponentiation to calculate x^y % mod
def quickmul(x: int, y: int) -> int:
ret, mul = 1, x
while y > 0:
if y % 2 == 1:
ret = ret * mul % mod
mul = mul * mul % mod
y //= 2
return ret
return quickmul(5, (n + 1) // 2) * quickmul(4, n // 2) % mod
714 - 2025-04-12 19:10:13 +0300 MSK
Find the Count of Good Integers
Links
Code
class Solution(object):
def __init__(self):
self.res = 0
self.visited = set()
def vectorToNumber(self, digits):
return int(''.join(map(str, digits)))
def totalPermutations(self, freqMap, total):
res = factorial(total)
for count in freqMap.values():
res //= factorial(count)
return res
def permsWithZero(self, freqMap, total):
if freqMap.get(0, 0) == 0:
return 0
freqMap[0] -= 1
res = factorial(total - 1)
for count in freqMap.values():
res //= factorial(count)
return res
def genPal(self, palin, left, right, divisor, total):
if left > right:
palinVal = self.vectorToNumber(palin)
if palinVal % divisor == 0:
freq = Counter(palin)
key = tuple(sorted(freq.items()))
if key not in self.visited:
self.res += self.totalPermutations(freq, total) - self.permsWithZero(freq.copy(), total)
self.visited.add(key)
return
for dig in range(1 if left == 0 else 0, 10):
palin[left] = palin[right] = dig
self.genPal(palin, left + 1, right - 1, divisor, total)
def countGoodIntegers(self, n, k):
self.res = 0
self.visited.clear()
self.genPal([0] * n, 0, n - 1, k, n)
return self.res
715 - 2025-04-11 20:06:54 +0300 MSK
Count Symmetric Integers
Links
Code
class Solution:
def countSymmetricIntegers(self, low: int, high: int) -> int:
count = 0
for num in range(low, high + 1):
s = str(num)
if len(s) % 2 == 0:
mid = len(s) // 2
if sum(map(int, s[:mid])) == sum(map(int, s[mid:])):
count += 1
return count
716 - 2025-04-10 19:50:16 +0300 MSK
Count the Number of Powerful Integers
Links
Code
class Solution:
def numberOfPowerfulInt(self, start: int, finish: int, limit: int, suffix: str) -> int:
def count_powerful_up_to(num: int) -> int:
num_str = str(num)
suffix_len = len(suffix)
prefix_len = len(num_str) - suffix_len
if prefix_len < 0:
return 0
dp = [[0] * 2 for _ in range(prefix_len + 1)]
dp[prefix_len][0] = 1
suffix_from_num = num_str[prefix_len:]
dp[prefix_len][1] = int(suffix_from_num) >= int(suffix)
for i in range(prefix_len - 1, -1, -1):
digit = int(num_str[i])
dp[i][0] = (limit + 1) * dp[i + 1][0]
if digit <= limit:
dp[i][1] = digit * dp[i + 1][0] + dp[i + 1][1]
else:
dp[i][1] = (limit + 1) * dp[i + 1][0]
return dp[0][1]
return count_powerful_up_to(finish) - count_powerful_up_to(start - 1)
717 - 2025-04-09 19:33:13 +0300 MSK
Minimum Operations to Make Array Values Equal to K
Links
Code
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
if not nums:
return -1
nums.sort(reverse=True)
if nums[-1] < k:
return -1
prev = nums[0]
if prev == k:
return 0
ops = 0
for num in nums[1:]:
if num == prev:
continue
ops += 1
prev = num
if num == k:
return ops
return ops + 1
718 - 2024-06-28 19:53:30 +0300 MSK
Maximum Total Importance of Roads
Links
Code
class Solution:
def maximumImportance(self, n: int, roads: List[List[int]]) -> int:
res = 0
cost = 1
conn = [0] * n
for road in roads:
conn[road[0]] += 1
conn[road[1]] += 1
conn.sort()
for con in conn:
res += con * cost
cost += 1
return res
719 - 2024-06-26 18:39:14 +0300 MSK
Balance a Binary Search Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
self.sortedArr = []
self.inorderTraverse(root)
return self.sortedArrayToBST(0, len(self.sortedArr) - 1)
def inorderTraverse(self, root: TreeNode) -> None:
if not root:
return
self.inorderTraverse(root.left)
self.sortedArr.append(root)
self.inorderTraverse(root.right)
def sortedArrayToBST(self, start: int, end: int) -> TreeNode:
if start > end:
return None
mid = (start + end) // 2
root = self.sortedArr[mid]
root.left = self.sortedArrayToBST(start, mid - 1)
root.right = self.sortedArrayToBST(mid + 1, end)
return root
720 - 2024-06-25 20:07:01 +0300 MSK
Binary Search Tree to Greater Sum Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
self.val = 0
def dfs(node):
if not node:
return
dfs(node.right)
self.val += node.val
node.val = self.val
dfs(node.left)
dfs(root)
return root
721 - 2024-06-24 15:55:17 +0300 MSK
Minimum Number of K Consecutive Bit Flips
Links
Code
class Solution:
def minKBitFlips(self, A: List[int], K: int) -> int:
n, flipped, res = len(A), 0, 0
fp = [0] * n
for i in range(n):
if i >= K:
flipped ^= fp[i - K]
if flipped == A[i]:
if i + K > n:
return -1
fp[i] = 1
flipped ^= 1
res += 1
return res
722 - 2024-06-23 14:38:18 +0300 MSK
Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
Links
Code
class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
decQ = collections.deque()
incQ = collections.deque()
ans = 0
left = 0
for right, num in enumerate(nums):
while decQ and num > decQ[-1]:
decQ.pop()
decQ.append(num)
while incQ and num < incQ[-1]:
incQ.pop()
incQ.append(num)
while decQ[0] - incQ[0] > limit:
if decQ[0] == nums[left]:
decQ.popleft()
if incQ[0] == nums[left]:
incQ.popleft()
left += 1
ans = max(ans, right - left + 1)
return ans
723 - 2024-06-22 16:33:20 +0300 MSK
Count Number of Nice Subarrays
Links
Code
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
for i in range(len(nums)):
nums[i] %= 2
prefix_count = [0] * (len(nums) + 1)
prefix_count[0] = 1
s = 0
ans = 0
for num in nums:
s += num
if s >= k:
ans += prefix_count[s - k]
prefix_count[s] += 1
return ans
724 - 2024-06-21 19:21:07 +0300 MSK
Grumpy Bookstore Owner
Links
Code
class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
ans = 0
total = sum((1 - grumpy[i]) * customers[i] for i in range(len(customers)))
window_all = 0
window_partial = 0
for i in range(len(customers)):
window_all += customers[i]
window_partial += (1 - grumpy[i]) * customers[i]
if i + 1 >= minutes:
ans = max(ans, total - window_partial + window_all)
left = i - minutes + 1
window_all -= customers[left]
window_partial -= (1 - grumpy[left]) * customers[left]
return ans
725 - 2024-06-19 19:59:31 +0300 MSK
Minimum Number of Days to Make m Bouquets
Links
Code
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
n=len(bloomDay)
if m*k>n: return -1
def f(d):
len, bouquet=0, 0
i=0
while i<n:
while i<n and bloomDay[i]<=d:
len+=1
if len==k:
bouquet+=1
len=0
i+=1
if i<n and bloomDay[i]>d: len=0
if bouquet>m: return True
i+=1
return bouquet>=m
l, r = min(bloomDay), max(bloomDay)
while l < r:
mid = l + (r - l) // 2
if f(mid):
r = mid
else:
l = mid + 1
return l
726 - 2024-06-17 15:39:57 +0300 MSK
Sum of Square Numbers
Links
Code
from math import sqrt
class Solution:
def judgeSquareSum(self, c: int) -> bool:
for a in range(int(sqrt(c)) + 1): # Iterate through all possible values of `a`
b = sqrt(c - a * a) # Compute `b` as the square root of `c - a^2`
if b == int(b): # Check if `b` is an integer
return True # If `b` is an integer, return true
return False # If no such pair `(a, b)` is found, return false
727 - 2024-06-15 13:32:54 +0300 MSK
IPO
Links
Code
class Solution:
def findMaximizedCapital(
self, k: int, w: int, profits: List[int], capital: List[int]
) -> int:
n = len(profits)
projects = [(capital[i], profits[i]) for i in range(n)]
projects.sort()
maxHeap = []
i = 0
for _ in range(k):
while i < n and projects[i][0] <= w:
heapq.heappush(maxHeap, -projects[i][1])
i += 1
if not maxHeap:
break
w -= heapq.heappop(maxHeap)
return w
728 - 2024-06-14 18:54:35 +0300 MSK
Minimum Increment to Make Array Unique
Links
Code
class Solution:
def minIncrementForUnique(self, nums: List[int]) -> int:
# nums = [3,2,1,2,1,7]
# [1,1,2,2,3,7]
# mySet = set({ num for num in nums }), 2+4
nums.sort()
numTracker = 0
minIncreament = 0
for num in nums:
numTracker = max(numTracker, num)
minIncreament += numTracker - num
numTracker += 1
return minIncreament
729 - 2024-06-13 10:32:12 +0300 MSK
Minimum Number of Moves to Seat Everyone
Links
Code
class Solution:
def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
seats.sort()
students.sort()
moves = 0
for i in range(len(seats)) :
moves += abs(seats[i] - students[i])
return moves
730 - 2024-06-12 19:59:15 +0300 MSK
Sort Colors
Links
Code
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zeros, ones, n = 0, 0, len(nums)
for num in nums:
if num == 0:
zeros += 1
elif num == 1:
ones += 1
for i in range(0, zeros):
nums[i] = 0
for i in range(zeros, zeros + ones):
nums[i] = 1
for i in range(zeros + ones, n):
nums[i] = 2
731 - 2024-06-11 20:57:06 +0300 MSK
Relative Sort Array
Links
Code
class Solution:
def relativeSortArray(self, arr1, arr2):
result = []
for i in range(len(arr2)):
for j in range(len(arr1)):
if arr1[j] == arr2[i]:
result.append(arr1[j])
arr1[j] = -1
arr1.sort()
for num in arr1:
if num != -1:
result.append(num)
return result
732 - 2024-06-10 13:15:44 +0300 MSK
Height Checker
Links
Code
class Solution:
def heightChecker(self, heights: List[int]) -> int:
return sum(h!=s for h, s in zip(heights, sorted(heights)))
733 - 2024-06-09 13:56:45 +0300 MSK
Subarray Sums Divisible by K
Links
Code
class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
count = 0
prefix_sum = 0
prefix_map = {0: 1}
for num in nums:
prefix_sum += num
mod = prefix_sum % k
if mod < 0:
mod += k
if mod in prefix_map:
count += prefix_map[mod]
prefix_map[mod] += 1
else:
prefix_map[mod] = 1
return count
734 - 2024-06-08 22:13:27 +0300 MSK
Continuous Subarray Sum
Links
Code
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
remainder_map = {0: -1}
cumulative_sum = 0
for i, num in enumerate(nums):
cumulative_sum += num
remainder = cumulative_sum % k
if remainder in remainder_map:
if i - remainder_map[remainder] > 1:
return True
else:
remainder_map[remainder] = i
return False
735 - 2024-06-07 18:18:51 +0300 MSK
Replace Words
Links
Code
class Solution:
def replaceWords(self, dict: List[str], sentence: str) -> str:
roots = set(dict)
words = sentence.split()
result = []
for word in words:
for i in range(len(word) + 1):
prefix = word[:i]
if prefix in roots:
result.append(prefix)
break
else:
result.append(word)
return ' '.join(result)
736 - 2024-06-06 18:22:03 +0300 MSK
Hand of Straights
Links
Code
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
# Step 1: Check if grouping is possible
if len(hand) % groupSize != 0:
return False
# Step 2: Count the occurrences of each card
count = Counter(hand)
# Step 3: Sort the unique card values
sorted_keys = sorted(count.keys())
# Step 4: Form consecutive groups
for key in sorted_keys:
if count[key] > 0: # If this card is still available
start_count = count[key]
# Check and form a group starting from `key`
for i in range(key, key + groupSize):
if count[i] < start_count:
return False
count[i] -= start_count
# Step 5: Return True if all groups are formed successfully
return True
737 - 2024-06-05 10:32:36 +0300 MSK
Find Common Characters
Links
Code
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
result = []
# Check each character from 'a' to 'z'
for char in range(ord('a'), ord('z') + 1):
char = chr(char)
min_count = float('inf') # Start with a very high number
# Find the minimum count of the character in all words
for word in words:
count = word.count(char) # Count the current character in the current word
min_count = min(min_count, count) # Keep track of the smallest count
if min_count == 0:
break # If the character is not in one of the words, we can skip further checking
# Add the character to the result list the required number of times
result.extend([char] * min_count)
return result
738 - 2024-06-03 15:40:20 +0300 MSK
Append Characters to String to Make Subsequence
Links
Code
class Solution:
def appendCharacters(self, s: str, t: str) -> int:
i, j = 0, 0 # Start both pointers at the beginning of s and t
while i < len(s) and j < len(t): # Continue until one of the strings is fully scanned
if s[i] == t[j]: # If characters match
j += 1 # Move the pointer in t forward
i += 1 # Always move the pointer in s forward
return len(t) - j # The number of characters in t not matched in s
739 - 2024-06-02 21:31:18 +0300 MSK
Student Attendance Record II
Links
Code
class Solution:
def checkRecord(self, n: int) -> int:
# Recursion + Cache
mod=10**9+7
#only @cache will lead to MLE
dp=[[[-1]*3 for _ in range(2)] for _ in range(n+1)]
def f(i, absent, late):
if absent>=2 or late>=3: return 0
if i==0: return 1
if dp[i][absent][late]!=-1:
return dp[i][absent][late]
ans=f(i-1, absent, 0)
ans+=f(i-1, absent, late+1)
ans+=f(i-1, absent+1, 0)
dp[i][absent][late]=ans%mod
return dp[i][absent][late]
return f(n, 0, 0)
740 - 2024-06-01 22:04:19 +0300 MSK
Single Number III
Links
Code
class Solution:
def singleNumber(self, nums: list[int]) -> list[int]:
n: int = len(nums)
result: list[int] = [0, 0]
index = 0
for i in range(n):
found = False
for j in range(n):
if i != j and nums[i] == nums[j]:
found = True
break
if not found:
result[index] = nums[i]
index += 1
if index == 2:
break
return result
741 - 2024-06-01 22:04:02 +0300 MSK
Count Triplets That Can Form Two Arrays of Equal XOR
Links
Code
class Solution:
def countTriplets(self, arr: List[int]) -> int:
n = len(arr)
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] ^ arr[i]
count = 0
for i in range(n):
for k in range(i + 1, n):
if prefix[i] == prefix[k + 1]:
count += (k - i)
return count
742 - 2024-06-01 22:03:45 +0300 MSK
Maximum Score Words Formed by Letters
Links
Code
class Solution:
def maxScoreWords(
self, words: List[str], letters: List[str], score: List[int]
) -> int:
lettersCounter = Counter(letters)
totalScore = 0
def explore(index, letterCounter, currScore):
nonlocal totalScore
totalScore = max(totalScore, currScore)
if index == len(words):
return
for i in range(index, len(words)):
tmpCounter = copy.deepcopy(letterCounter)
word = words[i]
wordScore = 0
isValid = True
for ch in word:
if ch in tmpCounter and tmpCounter[ch] > 0:
tmpCounter[ch] -= 1
wordScore += score[ord(ch) - ord("a")]
else:
isValid = False
break
if isValid:
explore(i + 1, tmpCounter, currScore + wordScore)
explore(0, lettersCounter, 0)
return totalScore
743 - 2024-06-01 22:01:30 +0300 MSK
Score of a String
Links
Code
class Solution:
def scoreOfString(self, s: str) -> int:
score = 0
for i in range(len(s) - 1):
score += abs(ord(s[i]) - ord(s[i + 1]))
return score
744 - 2024-05-29 12:47:46 +0300 MSK
Number of Steps to Reduce a Number in Binary Representation to One
Links
Code
class Solution:
def numSteps(self, s: str) -> int:
steps = 0
carry = 0
n = len(s) - 1
for i in range(n, 0, -1):
if int(s[i]) + carry == 1:
carry = 1
steps += 2
else:
steps += 1
return steps + carry
745 - 2024-05-28 20:05:20 +0300 MSK
Get Equal Substrings Within Budget
Links
Code
class Solution:
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
n = len(s)
start = 0
current_cost = 0
max_length = 0
for end in range(n):
current_cost += abs(ord(s[end]) - ord(t[end]))
while current_cost > maxCost:
current_cost -= abs(ord(s[start]) - ord(t[start]))
start += 1
max_length = max(max_length, end - start + 1)
return max_length
746 - 2024-05-27 10:56:18 +0300 MSK
Special Array With X Elements Greater Than or Equal X
Links
Code
class Solution:
def specialArray(self, nums: list[int]) -> int:
nums.sort()
n: int = len(nums)
def find_number_of_nums(cur_num) -> int:
left: int = 0
right: int = n - 1
first_index: int = n
while left <= right:
mid: int = (left + right) // 2
if nums[mid] >= cur_num:
first_index = mid
right = mid - 1
else:
left = mid + 1
return n - first_index
for candidate_number in range(1, n + 1, 1):
if candidate_number == find_number_of_nums(candidate_number):
return candidate_number
return -1
747 - 2024-05-26 20:44:15 +0300 MSK
Student Attendance Record II
Links
Code
class Solution:
def checkRecord(self, n: int) -> int:
temp: list[list[list[int]]] = [
[[-1 for _ in range(3)] for _ in range(2)] for _ in range(n)
] # temp[cur_ind][count_a][count_l]
MOD: int = 10**9 + 7
def check_all_records(cur_ind, count_a, count_l) -> int:
if cur_ind == n:
return 1
if temp[cur_ind][count_a][count_l] != -1:
return temp[cur_ind][count_a][count_l]
with_a_next: int = check_all_records(cur_ind + 1, count_a + 1, 0) if count_a == 0 else 0
with_l_next: int = 0 if count_l == 2 else check_all_records(cur_ind + 1, count_a, count_l + 1)
with_p_next: int = check_all_records(cur_ind + 1, count_a, 0)
total: int = (with_a_next + with_l_next + with_p_next) % MOD
temp[cur_ind][count_a][count_l] = total
return total
return check_all_records(0, 0, 0)
748 - 2024-05-25 22:59:58 +0300 MSK
Word Break II
Links
Code
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordSet = set(wordDict)
@cache
def helper(t):
combos = []
if not t:
return [""]
for i, _ in enumerate(t):
w = t[:i+1]
if w in wordSet:
combos.extend([
f'{w} {sentence}' if sentence else w
for sentence in helper(t[i+1:])
])
return combos
return helper(s)
749 - 2024-05-21 21:02:08 +0300 MSK
Subsets
Links
Code
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def backtrack(start, path):
result.append(path)
for i in range(start, len(nums)):
backtrack(i + 1, path + [nums[i]])
result = []
backtrack(0, [])
return result
750 - 2024-05-20 13:28:49 +0300 MSK
Sum of All Subset XOR Totals
Links
Code
class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
return reduce(operator.or_, nums) * 1 << (len(nums) - 1)
751 - 2024-05-19 15:08:43 +0300 MSK
Find the Maximum Sum of Node Values
Links
Code
class Solution:
def maximumValueSum(self, nums: list[int], k: int, edges: list[list[int]]) -> int:
n: int = len(nums)
temp: list[list[int]] = [[-1 for _ in range(2)] for _ in range(n)] # temp[current_index(node)][is_even]
def calculate_max(cur_ind, is_even) -> int: # cur_ind -> cur_index of the tree and is_even represents whether we have already changed (XOR) even or odd number of nodes
if cur_ind == n: # if we go to node which doesn't exist
return 0 if is_even else -float("inf")
if temp[cur_ind][is_even] != -1: # if we've already encountered this state
return temp[cur_ind][is_even]
# checking all possible variants (no XOR or XOR)
no_xor = nums[cur_ind] + calculate_max(cur_ind + 1, is_even) # we don't change the number of XOR nodes
with_xor = (nums[cur_ind] ^ k) + calculate_max(cur_ind + 1, not is_even) # we added 1 XORed node
mx_possible = max(no_xor, with_xor)
temp[cur_ind][is_even] = mx_possible
return mx_possible
return calculate_max(0, 1) # is_even == 1 because we have XORed 0 nodes which is even
752 - 2024-05-18 20:24:14 +0300 MSK
Distribute Coins in Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def distributeCoins(self, root: Optional[TreeNode]) -> int:
#move coins to parent DFS
def f(root, parent):
if root==None: return 0
moves=f(root.left, root)+f(root.right, root)
x=root.val-1
if parent!=None: parent.val+=x
moves+=abs(x)
return moves
return f(root, None)
753 - 2024-05-17 21:25:39 +0300 MSK
Delete Leaves With a Given Value
Links
Code
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def removeLeafNodes(self, root, target):
"""
:type root: TreeNode
:type target: int
:rtype: TreeNode
"""
if not root:
return None
root.left = self.removeLeafNodes(root.left, target)
root.right = self.removeLeafNodes(root.right, target)
if not root.left and not root.right and root.val == target:
return None
return root
754 - 2024-05-16 18:11:33 +0300 MSK
Evaluate Boolean Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def helper(self, root):
if root.val == 0 or root.val == 1:
return root.val == 1
elif root.val == 2:
return self.helper(root.left) or self.helper(root.right)
elif root.val == 3:
return self.helper(root.left) and self.helper(root.right)
return False
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
return self.helper(root)
755 - 2024-05-14 12:06:07 +0300 MSK
Path with Maximum Gold
Links
Code
class Solution:
roww = [1, -1, 0, 0]
coll = [0, 0, -1, 1]
def dfs(self, grid, x, y, n, m):
if x < 0 or x >= n or y < 0 or y >= m or grid[x][y] == 0:
return 0
curr = grid[x][y]
grid[x][y] = 0
localMaxGold = curr
for i in range(4):
newX = x + self.roww[i]
newY = y + self.coll[i]
localMaxGold = max(localMaxGold, curr + self.dfs(grid, newX, newY, n, m))
grid[x][y] = curr
return localMaxGold
def getMaximumGold(self, grid):
n = len(grid)
m = len(grid[0])
maxGold = 0
for i in range(n):
for j in range(m):
if grid[i][j] != 0:
maxGold = max(maxGold, self.dfs(grid, i, j, n, m))
return maxGold
756 - 2024-05-13 10:22:15 +0300 MSK
Score After Flipping Matrix
Links
Code
class Solution:
def matrixScore(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
res = (1 << (m - 1)) * n
for j in range(1, m):
val = 1 << (m - 1 - j)
set_count = 0
for i in range(n):
if grid[i][j] == grid[i][0]:
set_count += 1
res += max(set_count, n - set_count) * val
return res
757 - 2024-05-12 21:39:08 +0300 MSK
Largest Local Values in a Matrix
Links
Code
class Solution:
def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
n, res = len(grid), []
for i in range(1, n - 1):
temp_row = []
for j in range(1, n - 1):
temp = 0
for k in range(i - 1, i + 2):
for l in range(j - 1, j + 2):
temp = max(temp, grid[k][l])
temp_row.append(temp)
res.append(temp_row)
return res
758 - 2024-05-08 10:50:28 +0300 MSK
Relative Ranks
Links
Code
import heapq
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
heap = []
length = len(score)
scores = [0] * length
for i in range(length):
scores[i] = (score[i], i)
scores.sort(reverse=True)
ranks = {0: "Gold Medal", 1: "Silver Medal", 2: "Bronze Medal"}
for i in range(length):
_, idx = scores[i]
score[idx] = ranks.get(i, str(i + 1))
return score
759 - 2024-05-08 10:39:08 +0300 MSK
Relative Ranks
Links
Code
import heapq
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
heap = []
for i, athlete_score in enumerate(score):
heapq.heappush(heap, (-athlete_score, i))
i = 0
ranks = {0: "Gold Medal", 1: "Silver Medal", 2: "Bronze Medal"}
while heap:
_, athlete = heapq.heappop(heap)
rank = ranks.get(i, str(i + 1))
score[athlete] = rank
i += 1
return score
760 - 2024-05-07 10:56:39 +0300 MSK
Double a Number Represented as a Linked List
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
def func(head):
a=head.val*2
if head.next:
a+=func(head.next)
head.val=a%10
return a//10
a=func(head)
if a:
return ListNode(a,head)
return head
761 - 2024-05-06 16:47:26 +0300 MSK
Remove Nodes From Linked List
Links
Code
class Solution:
def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
stack = []
while cur:
while stack and stack[-1].val < cur.val:
stack.pop()
stack.append(cur)
cur = cur.next
nxt = None
while stack:
cur = stack.pop()
cur.next = nxt
nxt = cur
return cur
762 - 2024-05-04 18:08:36 +0300 MSK
Boats to Save People
Links
Code
func numRescueBoats(people []int, limit int) int {
sort.Ints(people)
numberOfBouts := 0
start := 0
end := len(people)-1
for start < end {
if people[start] + people[end] <= limit {
numberOfBouts++
start++
}else{
numberOfBouts++
}
end--
}
if start == end {
numberOfBouts++
}
return numberOfBouts
}
763 - 2024-05-03 17:41:51 +0300 MSK
Compare Version Numbers
Links
Code
func compareVersion(version1 string, version2 string) int {
rev1 := strings.Split(version1, ".")
rev2 := strings.Split(version2, ".")
// fmt.Println(rev1, rev2)
revInt1 := make([]int, len(rev1))
revInt2 := make([]int, len(rev2))
for i := 0; i < len(rev1); i++ {
revInt1[i], _ = strconv.Atoi(rev1[i])
}
for i := 0; i < len(rev2); i++ {
revInt2[i], _ = strconv.Atoi(rev2[i])
}
// fmt.Println(revInt1, revInt2)
i := 0
j := 0
for i < len(revInt1) && j < len(revInt2) {
if revInt1[i] < revInt2[j] {
return -1
} else if revInt1[i] > revInt2[j] {
return 1
}
i++
j++
}
for i < len(revInt1) {
if revInt1[i] > 0 {
return 1
}
i++
}
for j < len(revInt2) {
if revInt2[j] > 0 {
return -1
}
j++
}
return 0
}
764 - 2024-05-02 19:49:20 +0300 MSK
Largest Positive Integer That Exists With Its Negative
Links
Code
func findMaxK(nums []int) int {
alreadySeenNums := map[int]bool{}
res := -1
for _, num := range nums {
numAbs := int(math.Abs(float64(num)))
if numAbs < res {
continue
}
if alreadySeenNums[-num] {
res = numAbs
} else {
alreadySeenNums[num] = true
}
}
return res
}
765 - 2024-05-01 12:05:11 +0300 MSK
Find if Path Exists in Graph
Links
Code
type UnionFind struct {
parent []int
rank []int
}
func NewUnionFind(n int) *UnionFind {
parent := make([]int, n)
rank := make([]int, n)
for i := 0; i < n; i++ {
parent[i] = i
}
return &UnionFind{parent, rank}
}
func (uf *UnionFind) Find(u int) int {
if uf.parent[u] != u {
uf.parent[u] = uf.Find(uf.parent[u])
}
return uf.parent[u]
}
func (uf *UnionFind) UnionByRank(u, v int) {
i := uf.Find(u)
j := uf.Find(v)
if i == j {
return
}
if uf.rank[i] < uf.rank[j] {
uf.parent[i] = j
} else if uf.rank[i] > uf.rank[j] {
uf.parent[j] = i
} else {
uf.parent[i] = j
uf.rank[j]++
}
}
func validPath(n int, edges [][]int, source int, destination int) bool {
uf := NewUnionFind(n)
for _, edge := range edges {
u, v := edge[0], edge[1]
uf.UnionByRank(u, v)
}
return uf.Find(source) == uf.Find(destination)
}
766 - 2024-05-01 12:04:46 +0300 MSK
Number of Wonderful Substrings
Links
Code
func get(c rune) int {
return int(c - 'a')
}
func wonderfulSubstrings(word string) int64 {
cnt := make([]int64, 1024)
cnt[0] = 1
curState := 0
res := int64(0)
for _, c := range word {
curState ^= 1 << get(c)
res += cnt[curState]
for odd := 'a'; odd <= 'j'; odd++ {
oddState := curState ^ (1 << get(odd))
res += cnt[oddState]
}
cnt[curState]++
}
return res
}
767 - 2024-05-01 12:04:24 +0300 MSK
Sum of Distances in Tree
Links
Code
func sumOfDistancesInTree(n int, edges [][]int) []int {
graph := make(map[int][]int)
count := make([]int, n)
res := make([]int, n)
for _, edge := range edges {
u, v := edge[0], edge[1]
graph[u] = append(graph[u], v)
graph[v] = append(graph[v], u)
}
var dfs1 func(cur, parent int)
dfs1 = func(cur, parent int) {
count[cur] = 1
for _, child := range graph[cur] {
if child != parent {
dfs1(child, cur)
count[cur] += count[child]
res[cur] += res[child] + count[child]
}
}
}
var dfs2 func(cur, parent int)
dfs2 = func(cur, parent int) {
for _, child := range graph[cur] {
if child != parent {
res[child] = res[cur] + n - 2*count[child]
dfs2(child, cur)
}
}
}
dfs1(0, -1)
dfs2(0, -1)
return res
}
768 - 2024-05-01 12:02:52 +0300 MSK
Reverse Prefix of Word
Links
Code
func reversePrefix(word string, ch byte) string {
var natija string
for i := 0; i < len(word); i++ {
if word[i] == ch {
ch_index := i
for i >= 0 {
natija += string(word[i])
i--
}
return natija + word[ch_index + 1 : ]
}
}
return word
}
769 - 2024-04-29 21:04:33 +0300 MSK
Minimum Number of Operations to Make Array XOR Equal to K
Links
Code
func minOperations(nums []int, k int) int {
res := k
for _, n := range nums {
res ^= n
}
var ans int
for res > 0 {
ans += res%2
res = res >> 1
}
return ans
}
770 - 2024-04-26 10:34:22 +0300 MSK
Minimum Falling Path Sum II
Links
Code
type Triplet struct {
minSum int
secondMinSum int
minSumIndex int
}
func minFallingPathSum(grid [][]int) int {
return minFallingPathSumHelper(0, grid).minSum
}
func minFallingPathSumHelper(row int, grid [][]int) Triplet {
if row == len(grid) {
return Triplet{0, 0, 0}
}
nextRowTriplet := minFallingPathSumHelper(row+1, grid)
currentTriplet := Triplet{math.MaxInt32, math.MaxInt32, -1}
for col := 0; col < len(grid[0]); col++ {
var value int
if col != nextRowTriplet.minSumIndex {
value = grid[row][col] + nextRowTriplet.minSum
} else {
value = grid[row][col] + nextRowTriplet.secondMinSum
}
if value <= currentTriplet.minSum {
currentTriplet.secondMinSum = currentTriplet.minSum
currentTriplet.minSum = value
currentTriplet.minSumIndex = col
} else if value < currentTriplet.secondMinSum {
currentTriplet.secondMinSum = value
}
}
return currentTriplet
}
771 - 2024-04-25 20:32:24 +0300 MSK
Longest Ideal Subsequence
Links
Code
func longestIdealString(s string, k int) int {
dp := make([]int, 27)
n := len(s)
for i := n - 1; i >= 0; i-- {
cc := s[i]
idx := int(cc - 'a')
maxi := -1 << 31
left := max(idx-k, 0)
right := min(idx+k, 26)
for j := left; j <= right; j++ {
maxi = max(maxi, dp[j])
}
dp[idx] = maxi + 1
}
max := -1 << 31
for _, val := range dp {
if val > max {
max = val
}
}
return max
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
772 - 2024-04-24 15:06:12 +0300 MSK
N-th Tribonacci Number
Links
Code
func tribonacci(n int) int {
if n < 2 {
return n
}
dp := []int{0, 1, 1}
for i := 3; i <= n; i++ {
next := dp[0] + dp[1] + dp[2]
dp[0], dp[1], dp[2] = dp[1], dp[2], next
}
return dp[2]
}
773 - 2024-04-23 18:14:09 +0300 MSK
Minimum Height Trees
Links
Code
func findMinHeightTrees(n int, edges [][]int) []int {
counts := make([]int, n)
links := make([]int, n)
for _, edge := range edges {
links[edge[0]] ^= edge[1]
counts[edge[0]]++
links[edge[1]] ^= edge[0]
counts[edge[1]]++
}
Qu := make([]int, 0)
dists := make([]int, n)
for i := 0; i < n; i++ {
if counts[i] == 1 {
Qu = append(Qu, i)
}
}
stp := 1
for len(Qu) > 0 {
size := len(Qu)
for j := 0; j < size; j++ {
tmp := Qu[0]
Qu = Qu[1:]
links[links[tmp]] ^= tmp
counts[links[tmp]]--
if counts[links[tmp]] == 1 {
dists[links[tmp]] = int(math.Max(float64(stp), float64(dists[links[tmp]])))
Qu = append(Qu, links[tmp])
}
}
stp++
}
maxDist := 0
for _, dist := range dists {
if dist > maxDist {
maxDist = dist
}
}
res := make([]int, 0)
for i, dist := range dists {
if dist == maxDist {
res = append(res, i)
}
}
return res
}
774 - 2024-04-22 10:35:20 +0300 MSK
Find if Path Exists in Graph
Links
Code
type UnionFind struct {
parent []int
rank []int
}
func NewUnionFind(n int) *UnionFind {
parent := make([]int, n)
rank := make([]int, n)
for i := 0; i < n; i++ {
parent[i] = i
}
return &UnionFind{parent, rank}
}
func (uf *UnionFind) Find(u int) int {
if uf.parent[u] != u {
uf.parent[u] = uf.Find(uf.parent[u])
}
return uf.parent[u]
}
func (uf *UnionFind) UnionByRank(u, v int) {
i := uf.Find(u)
j := uf.Find(v)
if i == j {
return
}
if uf.rank[i] < uf.rank[j] {
uf.parent[i] = j
} else if uf.rank[i] > uf.rank[j] {
uf.parent[j] = i
} else {
uf.parent[i] = j
uf.rank[j]++
}
}
func validPath(n int, edges [][]int, source int, destination int) bool {
uf := NewUnionFind(n)
for _, edge := range edges {
u, v := edge[0], edge[1]
uf.UnionByRank(u, v)
}
return uf.Find(source) == uf.Find(destination)
}
775 - 2024-04-22 10:16:09 +0300 MSK
Open the Lock
Links
Code
import "strconv"
func openLock(deadends []string, target string) int {
pow10 := []int{1, 10, 100, 1000}
visit := make([]int, 10000) // 0: not visited, 1: visited through forward direction, -1: visited through backward direction, 2: deadends
for _, dead := range deadends {
num, _ := strconv.Atoi(dead)
visit[num] = 2
}
src := 0
dest, _ := strconv.Atoi(target)
steps := 0
dir := 1
if visit[src] == 2 || visit[dest] == 2 {
return -1
}
if src == dest {
return 0
}
forward := make([]int, 0)
backward := make([]int, 0)
forward = append(forward, src)
visit[src] = 1
backward = append(backward, dest)
visit[dest] = -1
for len(forward) > 0 && len(backward) > 0 {
if len(forward) > len(backward) {
forward, backward = backward, forward
dir = -dir
}
steps++
size := len(forward)
for j := 0; j < size; j++ {
cur := forward[0]
forward = forward[1:]
for _, p := range pow10 {
d := (cur / p) % 10
for _, i := range []int{-1, 1} {
z := d + i
if z == -1 {
z = 9
} else if z == 10 {
z = 0
}
next := cur + (z-d)*p
if visit[next] == -dir {
return steps
}
if visit[next] == 0 {
forward = append(forward, next)
visit[next] = dir
}
}
}
}
}
return -1
}
776 - 2024-04-20 21:02:52 +0300 MSK
Find All Groups of Farmland
Links
Code
func findFarmland(land [][]int) [][]int {
result := [][]int{}
m, n := len(land), len(land[0])
findFarmlandCoordinates := func(row, col int) []int {
coordinates := []int{row, col}
r, c := row, col
for r < m && land[r][col] == 1 {
r++
}
for c < n && land[row][c] == 1 {
c++
}
coordinates = append(coordinates, r-1, c-1)
for i := row; i < r; i++ {
for j := col; j < c; j++ {
land[i][j] = 0
}
}
return coordinates
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if land[i][j] == 1 {
result = append(result, findFarmlandCoordinates(i, j))
}
}
}
return result
}
777 - 2024-04-19 10:37:47 +0300 MSK
Island Perimeter
Links
Code
func islandPerimeter(grid [][]int) int {
islands := 0
neighbors := 0
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ {
if grid[i][j] == 1 {
islands++
if i-1 >= 0 && grid[i-1][j] == 1 {
neighbors++
}
if j-1 >= 0 && grid[i][j-1] == 1 {
neighbors++
}
}
}
}
return islands*4 - neighbors*2
}
778 - 2024-04-19 10:37:20 +0300 MSK
Number of Islands
Links
Code
func numIslands(grid [][]byte) int {
if len(grid) == 0 || len(grid[0]) == 0 {
return 0
}
rows := len(grid)
cols := len(grid[0])
islands := 0
var dfs func(row, col int)
dfs = func(row, col int) {
if row < 0 || col < 0 || row >= rows || col >= cols || grid[row][col] != '1' {
return
}
grid[row][col] = '0'
dfs(row-1, col)
dfs(row+1, col)
dfs(row, col-1)
dfs(row, col+1)
}
for row := 0; row < rows; row++ {
for col := 0; col < cols; col++ {
if grid[row][col] == '1' {
dfs(row, col)
islands++
}
}
}
return islands
}
779 - 2024-04-17 10:49:35 +0300 MSK
Smallest String Starting From Leaf
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func smallestFromLeaf(root *TreeNode) string {
ans := ""
var dfs func(node *TreeNode, text string)
dfs = func(node *TreeNode, text string) {
if node == nil {
return
}
text = string(rune(node.Val + 97)) + text
if node.Right == nil && node.Left == nil {
if ans == "" || ans > text {
ans = text
}
return
}
dfs(node.Left, text)
dfs(node.Right, text)
}
dfs(root, "")
return ans
}
780 - 2024-04-16 22:16:34 +0300 MSK
Add One Row to Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func addOneRow(root *TreeNode, val int, depth int) *TreeNode {
if root == nil {
return nil
}
if depth == 1 {
root = &TreeNode{Val: val, Left: root}
} else if (depth == 2) {
root.Left = &TreeNode{Val: val, Left: root.Left}
root.Right = &TreeNode{Val: val, Right: root.Right}
} else {
addOneRow(root.Left, val, depth - 1)
addOneRow(root.Right, val, depth - 1)
}
return root;
}
781 - 2024-04-15 09:51:02 +0300 MSK
Sum Root to Leaf Numbers
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumNumbers(root *TreeNode) int {
return dfs(root, 0)
}
func dfs(node *TreeNode, num int) int {
if node == nil {
return 0
}
if node.Left == nil && node.Right == nil {
return num * 10 + node.Val
}
return dfs(node.Left, num * 10 + node.Val) + dfs(node.Right, num * 10 + node.Val)
}
782 - 2024-04-15 09:49:56 +0300 MSK
Sum of Left Leaves
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumOfLeftLeaves(root *TreeNode) int {
if root == nil {
return 0
}
left := 0
if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
left = root.Left.Val
}
return left + sumOfLeftLeaves(root.Left) + sumOfLeftLeaves(root.Right)
}
783 - 2024-04-13 18:32:47 +0300 MSK
Maximal Rectangle
Links
Code
func maximalRectangle(matrix [][]byte) int {
heights := make([]int, len(matrix[0]) + 1)
heights[len(heights)-1] = -1
mx := 0
for _, row := range matrix {
for i := range row {
if row[i] == '1' {
heights[i]++
} else {
heights[i] = 0
}
}
stack := []int{}
for i, currentHeight := range heights {
for len(stack) > 0 && heights[stack[len(stack)-1]] > currentHeight {
prev := heights[stack[len(stack)-1]]
stack = stack[:len(stack)-1]
width := i
if len(stack) > 0 {
width = i - stack[len(stack)-1] - 1
}
mx = max(mx, prev * width)
}
stack = append(stack, i)
}
}
return mx
}
784 - 2024-04-12 10:40:19 +0300 MSK
Trapping Rain Water
Links
Code
func trap(height []int) int {
var waterStored int
leftElevationPoint, rightElevationPoint := 0, len(height)-1 // pointers for left and right elevations
maxLeftElevation, maxRightElevation := height[leftElevationPoint], height[rightElevationPoint] // max value of left and right elevation points
for leftElevationPoint < rightElevationPoint { // until left elevation point reaches right elevation point or right elevation point reaches left elevation point
if maxLeftElevation < maxRightElevation { // if max left elevation is smaller than max right elevation
leftElevationPoint++ // move the left elevation point by 1
if height[leftElevationPoint] > maxLeftElevation { // if height of current left elevation after moving is greater than max left elevation
maxLeftElevation = height[leftElevationPoint] // swap the max left elevation with current left elevation point value
}
waterStored += maxLeftElevation - height[leftElevationPoint] // store water with delta of max left elevation and current left elevation
} else {
rightElevationPoint-- // decrease the right elevation by 1
if height[rightElevationPoint] > maxRightElevation { // if height of current right elevation after decreasing is greater than max right elevation
maxRightElevation = height[rightElevationPoint] // swap the max right elevation with current right elevation point value
}
waterStored += maxRightElevation - height[rightElevationPoint] // store water with delta of max right elevation and current right elevation
}
}
return waterStored
}
785 - 2024-04-11 13:44:41 +0300 MSK
Remove K Digits
Links
Code
func removeKdigits(num string, k int) string {
res := make([]rune, 0)
for _, c := range num {
for len(res) > 0 && res[len(res) - 1] > c && k > 0 {
res = res[:len(res) - 1]
k--
}
if len(res) > 0 || c != '0' {
res = append(res, c)
}
}
for len(res) > 0 && k > 0 {
res = res[:len(res) - 1]
k--
}
if len(res) == 0 {
return "0"
}
return string(res)
}
786 - 2024-04-10 13:25:18 +0300 MSK
Reveal Cards In Increasing Order
Links
Code
func deckRevealedIncreasing(deck []int) []int {
n := len(deck)
sort.Ints(deck)
res := make([]int, n)
queue := make([]int, n)
for i := range queue {
queue[i] = i
}
for _, card := range deck {
idx := queue[0]
queue = queue[1:]
res[idx] = card
if len(queue) > 0 {
queue = append(queue, queue[0])
queue = queue[1:]
}
}
return res
}
787 - 2024-04-09 14:21:46 +0300 MSK
Time Needed to Buy Tickets
Links
Code
func timeRequiredToBuy(tickets []int, k int) int {
n := len(tickets)
d := tickets[k]
res := 0
for i := 0; i <= k; i++ {
res += min(d, tickets[i])
}
for i := k + 1; i < n; i++ {
res += min(d - 1, tickets[i])
}
return res
}
788 - 2024-04-08 11:25:34 +0300 MSK
Number of Students Unable to Eat Lunch
Links
Code
func countStudents(students []int, sandwiches []int) int {
req := make([]int, 2)
for _, student := range students {
req[student]++
}
for _, sandwich := range sandwiches {
if req[sandwich] == 0 {
return req[1 - sandwich]
} else {
req[sandwich]--
}
}
return 0
}
789 - 2024-04-07 11:42:18 +0300 MSK
Valid Parenthesis String
Links
Code
func checkValidString(s string) bool {
open := 0
openMax := 0
for _, char := range s {
switch char {
case '(':
open++
openMax++
case ')':
open--
openMax--
default:
open--
openMax++
}
if openMax < 0 {
return false
}
if open < 0 {
open = 0
}
}
return open == 0
}
790 - 2024-04-07 11:41:54 +0300 MSK
Minimum Remove to Make Valid Parentheses
Links
Code
type stack struct {
top int
v []byte
index []int
}
func minRemoveToMakeValid(s string) string {
stc := stack{top: -1}
// collect bad brackets
for i, v := range s {
if v == '(' {
stc.v = append(stc.v, '(')
stc.index = append(stc.index, i)
stc.top++
} else if v == ')' {
if stc.top > -1 && stc.v[stc.top] == '(' {
stc.v = stc.v[:stc.top]
stc.index = stc.index[:stc.top]
stc.top--
} else {
stc.v = append(stc.v, ')')
stc.index = append(stc.index, i)
stc.top++
}
}
}
// remove them
res := []byte{}
i := 0
for _, v := range stc.index {
res = append(res, s[i:v]...)
i = v + 1
}
// checking of end
if len(res) + len(stc.index) < len(s) {
res = append(res, s[i:]...)
}
return string(res)
}
791 - 2024-04-05 17:17:39 +0300 MSK
Make The String Great
Links
Code
func makeGood(s string) string {
stack := make([]byte, 0, len(s))
stack = append(stack, s[0])
for i := 1; i < len(s); i++ {
if len(stack) > 0 && getDiff(stack[len(stack)-1], s[i]) == 32 {
stack = stack[:len(stack)-1]
continue
}
stack = append(stack, s[i])
}
return string(stack)
}
func getDiff(a, b uint8) uint8 {
if b > a {
return b - a
}
return a - b
}
792 - 2024-04-04 16:06:45 +0300 MSK
Maximum Nesting Depth of the Parentheses
Links
Code
func maxDepth(s string) int {
maxDepth := 0
curDepth := 0
for _, ch := range s {
if ch == '(' {
curDepth++
maxDepth = max(maxDepth, curDepth)
} else if ch == ')' {
curDepth--
}
}
return maxDepth
}
793 - 2024-04-03 10:52:54 +0300 MSK
Word Search
Links
Code
func exist(board [][]byte, word string) bool {
if nLetters := len(board) * len(board[0]); nLetters < len(word) {
return false
}
for i := range board {
for j := range board[i] {
if dfs(i, j, 0, board, word, make(map[pair]struct{})) {
return true
}
}
}
return false
}
type pair struct {
r, c int
}
func dfs(r, c, i int, board [][]byte, word string, visited map[pair]struct{}) bool {
if i == len(word) {
return true
}
inBounds := r >= 0 && r < len(board) && c >= 0 && c < len(board[0])
if _, ok := visited[pair{r, c}]; !inBounds || ok || word[i] != board[r][c] {
return false
}
visited[pair{r, c}] = struct{}{}
up := dfs(r+1, c, i+1, board, word, visited)
down := dfs(r-1, c, i+1, board, word, visited)
right := dfs(r, c+1, i+1, board, word, visited)
left := dfs(r, c-1, i+1, board, word, visited)
delete(visited, pair{r, c})
return up || down || right || left
}
794 - 2024-04-02 17:28:57 +0300 MSK
Isomorphic Strings
Links
Code
func isIsomorphic(s string, t string) bool {
map1 := make([]int, 128) // Stores frequency of s
map2 := make([]int, 128) // Stores frequency of t
for i := 0; i < len(s); i++ {
sCh := s[i]
tCh := t[i]
if map1[sCh] == 0 && map2[tCh] == 0 {
map1[sCh] = int(tCh)
map2[tCh] = int(sCh)
} else if map1[sCh] != int(tCh) || map2[tCh] != int(sCh) {
return false
}
}
return true
}
795 - 2024-04-01 18:03:03 +0300 MSK
Length of Last Word
Links
Code
func lengthOfLastWord(s string) int {
length := len(s)
count := 0
for i := length - 1; i >= 0; i-- {
isSpace := s[i] == ' '
if isSpace && count != 0 {
return count
} else if isSpace {
continue
}
count++
}
return count
}
796 - 2024-03-31 10:58:30 +0300 MSK
Count Subarrays With Fixed Bounds
Links
Code
func countSubarrays(nums []int, minK int, maxK int) int64 {
var res int64
left := 0
pmin := -1
pmax := -1
for right, num := range nums {
if num < minK || num > maxK {
left = right + 1
pmin = -1
pmax = -1
} else {
if num == minK {
pmin = right
}
if num == maxK {
pmax = right
}
res += int64(max(0, min(pmin, pmax) - left + 1))
}
}
return res
}
797 - 2024-03-30 19:24:47 +0300 MSK
Subarrays with K Different Integers
Links
Code
func subarraysWithAtMostKDistinct(nums []int, k int) int {
if k == 0 {
return 0
}
countOccurrence := make(map[int]int)
differentIntegers := 0
left := 0
result := 0
for right := 0; right < len(nums); right++ {
countOccurrence[nums[right]]++
if countOccurrence[nums[right]] == 1 {
differentIntegers++
}
for differentIntegers > k {
countOccurrence[nums[left]]--
if countOccurrence[nums[left]] == 0 {
differentIntegers--
}
left++
}
result += right - left + 1
}
return result
}
func subarraysWithKDistinct(nums []int, k int) int {
return subarraysWithAtMostKDistinct(nums, k) - subarraysWithAtMostKDistinct(nums, k-1)
}
798 - 2024-03-29 14:30:16 +0300 MSK
Count Subarrays Where Max Element Appears at Least K Times
Links
Code
func countSubarrays(nums []int, k int) int64 {
maxValue := 0
var maxValueIds []int
var ans int64
for i, x := range nums {
if x > maxValue {
maxValue, ans, maxValueIds = x, 0, []int{}
}
if x == maxValue {
maxValueIds = append(maxValueIds, i)
}
if len(maxValueIds) >= k {
ans += int64(maxValueIds[len(maxValueIds)-k]) + 1
}
}
return ans
}
799 - 2024-03-28 19:02:58 +0300 MSK
Length of Longest Subarray With at Most K Frequency
Links
Code
func maxSubarrayLength(nums []int, k int) int {
i := 0
j := 0
n := len(nums)
ans := 1
mp := make(map[int]int)
for i < n {
mp[nums[i]]++
for mp[nums[i]] > k {
mp[nums[j]]--
j++
}
if i-j+1 > ans {
ans = i - j + 1
}
i++
}
return ans
}
800 - 2024-03-27 18:55:43 +0300 MSK
Subarray Product Less Than K
Links
Code
func numSubarrayProductLessThanK(nums []int, k int) int {
if k <= 1 {
return 0
}
l := 0
p := 1
res := 0
for r, num := range nums {
p *= num
for p >= k {
p /= nums[l]
l++
}
res += r - l + 1
}
return res
}
801 - 2024-03-26 10:04:37 +0300 MSK
First Missing Positive
Links
Code
func firstMissingPositive(nums []int) int {
n := len(nums)
for i := 0; i < n; i++ {
if nums[i] <= 0 || nums[i] > n {
nums[i] = n + 1
}
}
for i := 0; i < n; i++ {
val := abs(nums[i])
if val >= 1 && val <= n {
flagIndex := val - 1
if nums[flagIndex] > 0 {
nums[flagIndex] *= -1
}
}
}
for i := 1; i <= n; i++ {
if nums[i - 1] > 0 {
return i
}
}
return n + 1
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
802 - 2024-03-25 19:23:11 +0300 MSK
Find All Duplicates in an Array
Links
Code
func findDuplicates(nums []int) []int {
output := []int{}
for _, num := range nums {
idx := abs(num)
if nums[idx-1] < 0 {
output = append(output, idx)
} else {
nums[idx-1] *= -1
}
}
return output
}
func abs(num int) int {
if num < 0 {
return -num
}
return num
}
803 - 2024-03-24 14:27:34 +0300 MSK
Find the Duplicate Number
Links
Code
func findDuplicate(nums []int) int {
seen := make(map[int]struct{})
for _, num := range nums {
if _, ok := seen[num]; ok {
return num
}
seen[num] = struct{}{}
}
return -1
}
804 - 2024-03-24 14:27:17 +0300 MSK
Find the Duplicate Number
Links
Code
func findDuplicate(nums []int) int {
seen := make(map[int]struct{}, len(nums) - 1)
for _, num := range nums {
if _, ok := seen[num]; ok {
return num
}
seen[num] = struct{}{}
}
return -1
}
805 - 2024-03-23 20:51:44 +0300 MSK
Reorder List
Links
Code
func reorderList(head *ListNode) {
if head == nil || head.Next == nil {
return
}
middle := midNode(head)
newHead := middle.Next
middle.Next = nil
newHead = reverseLinkedList(newHead)
c1 := head
c2 := newHead
var f1, f2 *ListNode
for c1 != nil && c2 != nil {
// Backup
f1 = c1.Next
f2 = c2.Next
// Linking
c1.Next = c2
c2.Next = f1
// Move
c1 = f1
c2 = f2
}
}
func midNode(head *ListNode) *ListNode {
slow := head
fast := head
for fast.Next != nil && fast.Next.Next != nil {
slow = slow.Next
fast = fast.Next.Next
}
return slow
}
func reverseLinkedList(head *ListNode) *ListNode {
var prev, curr, forw *ListNode = nil, head, nil
for curr != nil {
forw = curr.Next
curr.Next = prev
prev = curr
curr = forw
}
return prev
}
806 - 2024-03-22 11:45:00 +0300 MSK
Palindrome Linked List
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func isPalindrome(head *ListNode) bool {
nodes := []int{}
for head != nil {
nodes = append(nodes, head.Val)
head = head.Next
}
length := len(nodes)
for i := range(length / 2) {
start, end := nodes[i], nodes[length-i-1]
if start != end {
return false
}
}
return true
}
807 - 2024-03-22 11:41:12 +0300 MSK
Reverse Linked List
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
if head == nil {
return nil
}
cur, next := head, head.Next
head.Next = nil
for next != nil {
cur, next, next.Next = next, next.Next, cur
}
return cur
}
808 - 2024-03-21 14:09:24 +0300 MSK
Reverse Linked List
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
if head == nil {
return nil
}
cur, next := head, head.Next
head.Next = nil
for next != nil {
cur, next, next.Next = next, next.Next, cur
}
return cur
}
809 - 2024-03-21 14:05:27 +0300 MSK
Reverse Linked List
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
if head == nil {
return nil
}
cur, next := head, head.Next
cur.Next = nil
for next != nil {
cur, next, next.Next = next, next.Next, cur
}
return cur
}
810 - 2024-03-21 13:53:28 +0300 MSK
Merge In Between Linked Lists
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode {
if list1 == nil {
return list2
}
list2Head, list2Tail := list2, list2
for list2 != nil {
list2Tail = list2
list2 = list2.Next
}
count := 0
list1Head := list1
for list1 != nil {
next := list1.Next
if count == a - 1 {
list1.Next = list2Head
} else if count == b {
list2Tail.Next = list1.Next
}
list1 = next
count++
}
return list1Head
}
811 - 2024-03-20 21:13:36 +0300 MSK
Task Scheduler
Links
Code
func leastInterval(tasks []byte, n int) int {
if n == 0 {
return len(tasks)
}
cnt := make([]int, 26)
for _, task := range tasks {
cnt[task - 'A']++
}
var maxCount, sameMaxCount int
for _, c := range cnt {
if c > maxCount {
maxCount = c
sameMaxCount = 1
} else if c == maxCount {
sameMaxCount++
}
}
res := (n + 1) * (maxCount - 1) + sameMaxCount
if (res > len(tasks)) {
return res
} else {
return len(tasks)
}
}
812 - 2024-03-20 21:12:54 +0300 MSK
Merge In Between Linked Lists
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode {
l := list1
for i := 1; i <= a - 1; i++ {
l = l.Next
}
prev := l
r := l
for i := a; i <= b + 1; i++ {
r = r.Next
prev.Next = nil
prev = r
}
list2Tail := list2
for list2Tail.Next != nil {
list2Tail = list2Tail.Next
}
l.Next = list2
list2Tail.Next = r
return list1
}
813 - 2024-03-18 19:30:56 +0300 MSK
Minimum Number of Arrows to Burst Balloons
Links
Code
func findMinArrowShots(points [][]int) int {
// Sort the balloons based on their end coordinates
sort.Slice(points, func(i, j int) bool {
return points[i][1] < points[j][1]
})
arrows := 1
prevEnd := points[0][1]
// Count the number of non-overlapping intervals
for i := 1; i < len(points); i++ {
if points[i][0] > prevEnd {
arrows++
prevEnd = points[i][1]
}
}
return arrows
}
814 - 2024-03-17 12:32:47 +0300 MSK
Contiguous Array
Links
Code
func findMaxLength(nums []int) int {
hashmap := make(map[int]int)
zeros, ones, maxLen := 0, 0, 0
hashmap[0] = -1
for i, num := range nums {
if num == 0 {
zeros++
} else {
ones++
}
diff := zeros - ones
if val, ok := hashmap[diff]; ok {
maxLen = max(maxLen, i - val)
} else {
hashmap[diff] = i
}
}
return maxLen
}
815 - 2024-03-17 12:32:06 +0300 MSK
Insert Interval
Links
Code
func insert(intervals [][]int, newInterval []int) [][]int {
var result [][]int
// Iterate through intervals and add non-overlapping intervals before newInterval
i := 0
for i < len(intervals) && intervals[i][1] < newInterval[0] {
result = append(result, intervals[i])
i++
}
// Merge overlapping intervals
for i < len(intervals) && intervals[i][0] <= newInterval[1] {
newInterval[0] = int(math.Min(float64(newInterval[0]), float64(intervals[i][0])))
newInterval[1] = int(math.Max(float64(newInterval[1]), float64(intervals[i][1])))
i++
}
// Add merged newInterval
result = append(result, newInterval)
// Add non-overlapping intervals after newInterval
for i < len(intervals) {
result = append(result, intervals[i])
i++
}
return result
}
816 - 2024-03-15 20:15:18 +0300 MSK
Product of Array Except Self
Links
Code
func productExceptSelf(nums []int) []int {
n := len(nums)
res := make([]int, n)
preProduct := 1
for i := 0; i < n; i++ {
res[i] = preProduct
preProduct *= nums[i]
}
sufProduct := 1
for i := n - 1; i >= 0; i-- {
res[i] *= sufProduct
sufProduct *= nums[i]
}
return res
}
817 - 2024-03-14 19:06:22 +0300 MSK
Binary Subarrays With Sum
Links
Code
func numSubarraysWithSum(nums []int, goal int) int {
hashmap := make(map[int]int)
hashmap[0] = 1
sum := 0
count := 0
for _, num := range nums {
sum += num
rem := sum - goal
if val, ok := hashmap[rem]; ok {
count += val
}
hashmap[sum]++
}
return count
}
818 - 2024-03-13 19:53:19 +0300 MSK
Find the Pivot Integer
Links
Code
func getSum(x int) int {
return x * (x + 1) / 2
}
func pivotInteger(n int) int {
sum := getSum(n)
l, r := 1, n
for l <= r {
m := (l + r) / 2
firstPart := getSum(m)
secondPart := sum - firstPart + m
if firstPart == secondPart {
return m
} else if firstPart > secondPart {
r = m - 1
} else {
l = m + 1
}
}
return -1
}
819 - 2024-03-12 19:08:41 +0300 MSK
Remove Zero Sum Consecutive Nodes from Linked List
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeZeroSumSublists(head *ListNode) *ListNode {
dummy := &ListNode{0, head}
prefixSumToNode := make(map[int]*ListNode)
prefixSum := 0
for current := dummy; current != nil; current = current.Next {
prefixSum += current.Val
if prev, found := prefixSumToNode[prefixSum]; found {
toRemove := prev.Next
p := prefixSum
if toRemove != nil {
p += toRemove.Val
}
for toRemove != nil && p != prefixSum {
delete(prefixSumToNode, p)
toRemove = toRemove.Next
if toRemove != nil {
p += toRemove.Val
}
}
prev.Next = current.Next
} else {
prefixSumToNode[prefixSum] = current
}
}
return dummy.Next
}
820 - 2024-03-11 19:30:24 +0300 MSK
Custom Sort String
Links
Code
func customSortString(order string, s string) string {
count := make([]int, 26)
for _, c := range s {
count[c-'a']++
}
var result strings.Builder
for _, c := range order {
result.WriteString(strings.Repeat(string(c), count[c-'a']))
count[c-'a'] = 0
}
for i := 0; i < 26; i++ {
result.WriteString(strings.Repeat(string('a'+i), count[i]))
}
// UPVOTE :)
return result.String()
}
821 - 2024-03-10 22:58:44 +0300 MSK
Intersection of Two Arrays
Links
Code
func intersection(nums1 []int, nums2 []int) []int {
seen := make([]int, 1000)
for i := range nums1 {
seen[nums1[i]]++
}
res := make([]int, 0)
for i := range nums2 {
if seen[nums2[i]] > 0 {
res = append(res, nums2[i])
seen[nums2[i]] = 0
}
}
return res
}
822 - 2024-03-09 19:01:11 +0300 MSK
Count Elements With Maximum Frequency
Links
Code
func maxFrequencyElements(nums []int) int {
mapCount := make(map[int]int)
for _, val := range nums {
mapCount[val]++
}
count := 0
max := -1
for _, freq := range mapCount {
if freq > max {
max = freq
}
}
for _, freq := range mapCount {
if freq == max {
count += max
}
}
return count
}
823 - 2024-03-09 18:59:53 +0300 MSK
Minimum Common Value
Links
Code
func getCommon(nums1 []int, nums2 []int) int {
var l, r int
for l < len(nums1) && r < len(nums2) {
switch {
case nums1[l] == nums2[r]:
return nums1[l]
case nums1[l] < nums2[r]:
l++
default:
r++
}
}
return -1
}
824 - 2024-03-07 19:08:46 +0300 MSK
Middle of the Linked List
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func middleNode(head *ListNode) *ListNode {
if head.Next == nil {
return head
}
slow, fast := head, head.Next
move := true
for fast.Next != nil {
if move {
slow = slow.Next
move = false
} else {
move = true
}
fast = fast.Next
}
if move {
return slow.Next
}
return slow
}
825 - 2024-03-07 19:07:46 +0300 MSK
Middle of the Linked List
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func middleNode(head *ListNode) *ListNode {
if head.Next == nil {
return head
}
slow, fast := head, head.Next
move := true
for fast.Next != nil {
if move {
slow = slow.Next
move = false
} else {
move = true
}
fast = fast.Next
}
if move {
slow = slow.Next
}
return slow
}
826 - 2024-03-06 16:05:23 +0300 MSK
Linked List Cycle
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
nodes := map[*ListNode]struct{}{}
for head != nil {
if _, ok := nodes[head]; ok {
return true
}
nodes[head] = struct{}{}
head = head.Next
}
return false
}
827 - 2024-03-05 11:52:38 +0300 MSK
Minimum Length of String After Deleting Similar Ends
Links
Code
func minimumLength(s string) int {
left := 0
right := len(s) - 1
for left < right {
lc := s[left]
rc := s[right]
if lc != rc {
return right - left + 1
}
for left + 1 < right && lc == s[left + 1] {
left++
}
for left < right - 1 && rc == s[right - 1] {
right--
}
right--
left++
}
return right - left + 1
}
828 - 2024-03-04 16:21:41 +0300 MSK
Bag of Tokens
Links
Code
func bagOfTokensScore(tokens []int, power int) int {
n := len(tokens)
sort.Ints(tokens)
res := 0
l := 0
r := n - 1
for l <= r {
for l <= r && power >= tokens[l] {
power -= tokens[l]
l++
res++
}
if res == 0 {
break
}
if r - l + 1 <= 2 {
break
}
power += tokens[r]
r--
res--
}
return res
}
829 - 2024-03-03 10:57:46 +0300 MSK
Remove Nth Node From End of List
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
res := &ListNode{0, head}
lead := res
for i := 0; i <= n; i++ {
lead = lead.Next
}
cur := res
for lead != nil {
cur = cur.Next
lead = lead.Next
}
cur.Next = cur.Next.Next
return res.Next
}
830 - 2024-03-02 15:59:13 +0300 MSK
Squares of a Sorted Array
Links
Code
func sortedSquares(nums []int) []int {
for i, num := range nums {
if num < 0 {
nums[i] = -num
} else {
break
}
}
slices.Sort(nums)
for i, num := range nums {
nums[i] = num * num
}
return nums
}
831 - 2024-03-02 15:57:16 +0300 MSK
Squares of a Sorted Array
Links
Code
func sortedSquares(nums []int) []int {
for i, num := range nums {
nums[i] = num * num
}
slices.Sort(nums)
return nums
}
832 - 2024-03-02 15:56:40 +0300 MSK
Squares of a Sorted Array
Links
Code
func sortedSquares(nums []int) []int {
for i, num := range nums {
if num < 0 {
nums[i] = -num
}
}
slices.Sort(nums)
for i, num := range nums {
nums[i] = num * num
}
return nums
}
833 - 2024-03-01 18:28:31 +0300 MSK
Maximum Odd Binary Number
Links
Code
func maximumOddBinaryNumber(s string) string {
l := len(s)
res := make([]byte, l)
index0, index1 := l-2, l-1
for i := 0; i < l; i++ {
if s[i] == '0' {
res[index0] = '0'
index0--
} else {
res[index1] = '1'
index1 = (index1 + 1) % l
}
}
return string(res)
}
834 - 2024-02-29 17:38:44 +0300 MSK
Even Odd Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isEvenOddTree(root *TreeNode) bool {
q := []*TreeNode{root}
for i:= 0; len(q) > 0; i++ {
var prev *TreeNode
for _, node := range q {
q = q[1:]
if i % 2 == 0 && node.Val % 2 != 1 {
return false
}
if i % 2 == 1 && node.Val % 2 != 0 {
return false
}
if prev != nil && i % 2 == 0 && prev.Val >= node.Val {
return false
}
if prev != nil && i % 2 == 1 && prev.Val <= node.Val {
return false
}
prev = node
if node.Left != nil {
q = append(q, node.Left)
}
if node.Right != nil {
q = append(q, node.Right)
}
}
}
return true
}
835 - 2024-02-28 12:31:13 +0300 MSK
Find Bottom Left Tree Value
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findBottomLeftValue(root *TreeNode) int {
_, val := getBottomLeft(root)
return val
}
func getBottomLeft(root *TreeNode) (int, int) {
left, right := root.Left, root.Right
if right == nil && left == nil {
return 0, root.Val
}
if right == nil {
depth, val := getBottomLeft(root.Left)
return 1 + depth, val
}
if left == nil {
depth, val := getBottomLeft(root.Right)
return 1 + depth, val
}
leftDepth, leftVal := getBottomLeft(root.Left)
rightDepth, rightVal := getBottomLeft(root.Right)
if rightDepth > leftDepth {
return 1 + rightDepth, rightVal
}
return 1 + leftDepth, leftVal
}
836 - 2024-02-27 19:25:53 +0300 MSK
Diameter of Binary Tree
Links
Code
var maxD int
func diameterOfBinaryTree(root *TreeNode) int {
maxD = 0
find(root)
return maxD
}
func find(root *TreeNode) int {
if root == nil {
return 0
}
left := find(root.Left)
right := find(root.Right)
localMax := left + right
maxD = max(maxD, localMax)
return max(left, right) + 1
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
837 - 2024-02-26 19:57:46 +0300 MSK
Same Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSameTree(p *TreeNode, q *TreeNode) bool {
if p == nil && q == nil {
return true
}
if p == nil || q == nil || p.Val != q.Val {
return false
}
return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
}
838 - 2024-02-25 20:04:05 +0300 MSK
Greatest Common Divisor Traversal
Links
Code
func canTraverseAllPairs(nums []int) bool {
if len(nums) == 1 {
return true
}
n := len(nums)
maxElement := nums[0]
minElement := nums[0]
for _, num := range nums {
if num > maxElement {
maxElement = num
}
if num < minElement {
minElement = num
}
}
if minElement == 1 {
return false
}
factorArray := factorsCalculator(maxElement)
parent := make([]int, maxElement+1)
rank := make([]int, maxElement+1)
for i := 0; i <= maxElement; i++ {
parent[i] = i
rank[i] = 1
}
for _, num := range nums {
x := num
for x > 1 {
p := factorArray[x]
union(parent, rank, p, num)
for x%p == 0 {
x = x / p
}
}
}
p := find(parent, nums[0])
for i := 1; i < n; i++ {
if find(parent, nums[i]) != p {
return false
}
}
return true
}
func factorsCalculator(n int) []int {
dp := make([]int, n+2)
for i := 0; i < len(dp); i++ {
dp[i] = i
}
for i := 2; i <= n; i++ {
if dp[i] == i {
for j := i * 2; j <= n; j += i {
if dp[j] == j {
dp[j] = i
}
}
}
}
return dp
}
func find(parent []int, a int) int {
if parent[a] == a {
return a
}
parent[a] = find(parent, parent[a])
return parent[a]
}
func union(parent []int, rank []int, a int, b int) {
a = find(parent, a)
b = find(parent, b)
if a == b {
return
}
if rank[a] < rank[b] {
a, b = b, a
}
parent[b] = a
rank[a] += rank[b]
}
839 - 2024-02-24 15:45:37 +0300 MSK
Find All People With Secret
Links
Code
package main
import (
"sort"
)
func find(groups []int, index int) int {
for index != groups[index] {
index = groups[index]
}
return index
}
func findAllPeople(n int, meetings [][]int, firstPerson int) []int {
groups := make([]int, 100000)
var result []int
var temp []int
for i := 0; i < n; i++ {
groups[i] = i
}
groups[firstPerson] = 0
sort.Slice(meetings, func(i, j int) bool {
return meetings[i][2] < meetings[j][2]
})
i := 0
for i < len(meetings) {
currentTime := meetings[i][2]
temp = temp[:0]
for i < len(meetings) && meetings[i][2] == currentTime {
g1 := find(groups, meetings[i][0])
g2 := find(groups, meetings[i][1])
groups[max(g1, g2)] = min(g1, g2)
temp = append(temp, meetings[i][0], meetings[i][1])
i++
}
for _, j := range temp {
if find(groups, j) != 0 {
groups[j] = j
}
}
}
for j := 0; j < n; j++ {
if find(groups, j) == 0 {
result = append(result, j)
}
}
return result
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
840 - 2024-02-23 12:30:25 +0300 MSK
Cheapest Flights Within K Stops
Links
Code
type Connection struct {
city int
cost int
}
type queue []Connection
func (q *queue) push(c Connection) {
q1 := []Connection{c}
*q = append(*q, q1...)
}
func (q *queue) pop() (bool, Connection) {
if q.isEmpty() {
return false, Connection{}
} else {
elem := (*q)[0]
*q = (*q)[1:]
return true, elem
}
}
func (q queue) isEmpty() bool {
return q.size() <= 0
}
func (q queue) size() int {
return len(q)
}
func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int {
minCost := math.MaxInt64
fQueue := new(queue)
fQueue.push(Connection{src, 0})
maxStops := k + 1
costOfFlights := make([][]int, n)
for i := range costOfFlights {
costOfFlights[i] = make([]int, n)
}
flightsMap := make(map[int][]int)
for _, v := range flights {
if _, ok := flightsMap[v[0]]; ok {
flightsMap[v[0]] = append(flightsMap[v[0]], v[1])
} else {
flightsMap[v[0]] = []int{v[1]}
}
costOfFlights[v[0]][v[1]] = v[2]
}
cityPathCost := make([]int, n) // path cost from source
for i := range cityPathCost {
cityPathCost[i] = math.MaxInt64
}
cityPathCost[src] = 0
for !fQueue.isEmpty() && maxStops >= 0 {
size := fQueue.size()
maxStops--
for size > 0 {
_, c := fQueue.pop()
size--
if c.city == dst {
if minCost > c.cost {
minCost = c.cost
}
continue
}
for _, v := range flightsMap[c.city] {
newCost := c.cost + costOfFlights[c.city][v]
if cityPathCost[v] > newCost {
fQueue.push(Connection{v, newCost})
cityPathCost[v] = newCost
}
}
}
}
if minCost == math.MaxInt64 {
minCost = -1
}
return minCost
}
841 - 2024-02-22 11:20:36 +0300 MSK
Find the Town Judge
Links
Code
func findJudge(n int, trust [][]int) int {
fromTo := make([][]int, n)
toFrom := make([][]int, n)
for _, trustArray := range trust {
from, to := trustArray[0], trustArray[1]
fromTo[from-1] = append(fromTo[from-1], to)
toFrom[to-1] = append(toFrom[to-1], from)
}
for i, from := range toFrom {
if len(from) == n - 1 && len(fromTo[i]) == 0 {
return i + 1
}
}
return -1
}
842 - 2024-02-21 11:42:07 +0300 MSK
Bitwise AND of Numbers Range
Links
Code
class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
shift = 0
while left != right:
left >>= 1
right >>= 1
shift += 1
return left << shift
843 - 2024-02-20 18:21:21 +0300 MSK
Missing Number
Links
Code
import operator
class Solution:
def missingNumber(self, nums: List[int]) -> int:
return reduce(
operator.xor,
nums,
reduce(operator.xor, tuple(range(len(nums) + 1)), 0)
)
844 - 2024-02-20 18:19:05 +0300 MSK
Missing Number
Links
Code
import operator
class Solution:
def missingNumber(self, nums: List[int]) -> int:
nums.extend(range(len(nums) + 1))
return reduce(operator.xor, nums, 0)
845 - 2024-02-20 18:16:37 +0300 MSK
Missing Number
Links
Code
import operator
class Solution:
def missingNumber(self, nums: List[int]) -> int:
length = len(nums)
return reduce(operator.xor, range(length), reduce(operator.xor, nums, length))
846 - 2024-02-20 15:10:36 +0300 MSK
Missing Number
Links
Code
class Solution:
def missingNumber(self, nums: List[int]) -> int:
def xor(total: int, i: int) -> int:
return total ^ nums[i] ^ (i + 1)
return reduce(xor, chain((0, ), range(len(nums))))
847 - 2024-02-19 11:56:55 +0300 MSK
Power of Two
Links
Code
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (n - 1) == 0
848 - 2024-02-18 12:45:46 +0300 MSK
Meeting Rooms III
Links
Code
class Solution:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
unused_rooms, used_rooms = list(range(n)), []
heapify(unused_rooms)
meeting_count = [0] * n
for start, end in sorted(meetings):
while used_rooms and used_rooms[0][0] <= start:
_, room = heappop(used_rooms)
heappush(unused_rooms, room)
if unused_rooms:
room = heappop(unused_rooms)
heappush(used_rooms, [end, room])
else:
room_availability_time, room = heappop(used_rooms)
heappush(
used_rooms,
[room_availability_time + end - start, room]
)
meeting_count[room] += 1
return meeting_count.index(max(meeting_count))
849 - 2024-02-17 15:07:38 +0300 MSK
Furthest Building You Can Reach
Links
Code
class Solution:
def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
heap = []
i = 0
length = len(heights)
for i in range(length - 1):
diff = heights[i + 1] - heights[i]
if diff <= 0:
continue
bricks -= diff
heapq.heappush(heap, -diff)
if bricks < 0:
bricks += -heapq.heappop(heap)
ladders -= 1
if ladders < 0:
return i
return length - 1
850 - 2024-02-17 15:03:52 +0300 MSK
Furthest Building You Can Reach
Links
Code
class Solution:
def furthestBuilding(self, h: List[int], b: int, l: int) -> int:
p = []
i = 0
for i in range(len(h) - 1):
diff = h[i + 1] - h[i]
if diff <= 0:
continue
b -= diff
x = heapq.heappush(p, -diff)
print(x)
if b < 0:
b += -heapq.heappop(p)
l -= 1
if l < 0:
return i
return len(h)-1
851 - 2024-02-16 18:29:09 +0300 MSK
Least Number of Unique Integers after K Removals
Links
Code
class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
counter = defaultdict(int)
for num in arr:
counter[num] += 1
nums = [(count, num) for num, count in counter.items()]
nums.sort()
removed = 0
for count, num in nums:
if k < count:
break
k -= count
removed += 1
return len(counter) - removed
852 - 2024-02-15 12:51:25 +0300 MSK
Find Polygon With the Largest Perimeter
Links
Code
class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort()
previous_elements_sum = 0
ans = -1
for num in nums:
if num < previous_elements_sum:
ans = num + previous_elements_sum
previous_elements_sum += num
return ans
853 - 2024-02-14 10:48:17 +0300 MSK
Rearrange Array Elements by Sign
Links
Code
class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
res = []
pos, neg = [], []
length = len(nums)
for i in range(length):
num = nums[i]
if num > 0:
pos.append(num)
else:
neg.append(num)
pos.reverse()
neg.reverse()
while pos and neg:
res.extend((pos.pop(), neg.pop()))
return res
854 - 2024-02-13 16:10:55 +0300 MSK
Find First Palindromic String in the Array
Links
Code
class Solution:
def firstPalindrome(self, words: List[str]) -> str:
for s in words:
for i in range(len(s) // 2):
if s[i] != s[-i - 1]:
break
else:
return s
return ""
855 - 2024-02-12 12:50:44 +0300 MSK
Majority Element
Links
Code
class Solution:
def majorityElement(self, nums: List[int]) -> int:
counter = defaultdict(int)
half = len(nums) // 2
for num in nums:
counter[num] += 1
if counter[num] > half:
return num
raise Exception()
856 - 2024-02-11 16:20:27 +0300 MSK
Cherry Pickup II
Links
Code
class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
n = len(grid)
m = len(grid[0])
# Create 3D DP table with initial values of 0
dp = [[[0] * m for _ in range(m)] for _ in range(n)]
# Set the starting point value (top-left and top-right corner)
cherries = 0
dp[0][0][m - 1] = grid[0][0] + grid[0][m - 1]
# Iterate through each row from second onwards
for i in range(1, n):
# Iterate through each column for robot 1
for j in range(m):
# Iterate through each column for robot 2
for k in range(m):
# Skip invalid states:
# - Both robots in the same row (j > i)
# - Robot 2 left of robot 1 (k < m - i - 1)
# - Robot 1 further right than robot 2 (j > k)
if j > i or k < m - i - 1 or j > k:
continue
# Base case: no moves possible, use previous state
dp[i][j][k] = dp[i - 1][j][k]
# Explore moves for robot 1:
# - Up-diagonal with robot 2 at same position
if j - 1 >= 0:
dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - 1][k])
# - Up-diagonal with robot 2 one step left/right
if j - 1 >= 0 and k - 1 >= 0:
dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - 1][k - 1])
if j - 1 >= 0 and k + 1 < m:
dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - 1][k + 1])
# Explore moves for robot 2:
# - Up-diagonal with robot 1 at same position
if j + 1 < m:
dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j + 1][k])
# - Up-diagonal with robot 1 one step left/right
if j + 1 < m and k - 1 >= 0:
dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j + 1][k - 1])
if j + 1 < m and k + 1 < m:
dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j + 1][k + 1])
# Explore horizontal moves for both robots:
# - Both robots move left
if k - 1 >= 0:
dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j][k - 1])
# - Both robots move right
if k + 1 < m:
dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j][k + 1])
# Add cherries only if robots are in different positions
if j != k:
dp[i][j][k] += grid[i][j] + grid[i][k]
else:
dp[i][j][k] += grid[i][j] # Only one robot picks if they land in the same cell
# Update maximum cherries collected so far
cherries = max(cherries, dp[i][j][k])
return cherries
857 - 2024-02-10 15:12:54 +0300 MSK
Palindromic Substrings
Links
Code
class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
palindrome = [[False] * n for _ in range(n)]
ans = 0
for i in range(n):
palindrome[i][i] = True
ans += 1
for i in range(n - 1):
if s[i] == s[i + 1]:
palindrome[i][i + 1] = True
ans += 1
for length in range(3, n + 1):
for i in range(n - length + 1):
if s[i] == s[i + length - 1] and palindrome[i + 1][i + length - 2]:
palindrome[i][i + length - 1] = True
ans += 1
return ans
858 - 2024-02-09 19:12:32 +0300 MSK
Largest Divisible Subset
Links
Code
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
nums.sort()
n = len(nums)
dp = [1] * n
max_size, max_index = 1, 0
for i in range(1, n):
for j in range(i):
if nums[i] % nums[j] == 0:
dp[i] = max(dp[i], dp[j] + 1)
if dp[i] > max_size:
max_size = dp[i]
max_index = i
result = []
num = nums[max_index]
for i in range(max_index, -1, -1):
if num % nums[i] == 0 and dp[i] == max_size:
result.append(nums[i])
num = nums[i]
max_size -= 1
return result
859 - 2024-02-08 15:50:03 +0300 MSK
Perfect Squares
Links
Code
class Solution:
def numSquares(self, n: int) -> int:
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
min_val = float('inf')
j = 1
while j * j <= i:
min_val = min(min_val, dp[i - j * j] + 1)
j += 1
dp[i] = min_val
return dp[n]
860 - 2024-02-07 10:59:44 +0300 MSK
Sort Characters By Frequency
Links
Code
class Solution:
def frequencySort(self, s: str) -> str:
counter = defaultdict(int)
for char in s:
counter[char] += 1
pq = [(-freq, char) for char, freq in counter.items()]
heapq.heapify(pq)
result = []
while pq:
freq, char = heapq.heappop(pq)
result.append(char * -freq)
return "".join(result)
861 - 2024-02-07 10:54:21 +0300 MSK
Sort Characters By Frequency
Links
Code
class Solution:
def frequencySort(self, s: str) -> str:
counter = {}
for char in s:
if char not in counter:
counter[char] = -ord(char)
counter[char] -= 100
return "".join(sorted(s, key=lambda val: counter[val]))
862 - 2024-02-07 10:52:55 +0300 MSK
Sort Characters By Frequency
Links
Code
class Solution:
def frequencySort(self, s: str) -> str:
counter = {}
for char in s:
if char not in counter:
counter[char] = ord(char)
counter[char] += 100
return "".join(sorted(s, key=lambda val: -counter[val]))
863 - 2024-02-07 10:49:08 +0300 MSK
Sort Characters By Frequency
Links
Code
class Solution:
def frequencySort(self, s: str) -> str:
counter = defaultdict(int)
for char in s:
counter[char] += 1
return "".join(sorted(s, key=lambda val: -(ord(val) + counter[val] * 100)))
864 - 2024-02-06 09:02:52 +0300 MSK
Group Anagrams
Links
Code
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = defaultdict(list)
for anagram in strs:
anagrams[tuple(sorted(anagram))].append(anagram)
return anagrams.values()
865 - 2024-02-05 10:12:58 +0300 MSK
First Unique Character in a String
Links
Code
class Solution:
def firstUniqChar(self, s: str) -> int:
counter = [0] * 26
for char in s:
idx = ord(char) - ord('a')
if counter[idx] in (0, 1):
counter[idx] += 1
for i in range(len(s)):
if counter[ord(s[i]) - ord('a')] == 1:
return i
return -1
866 - 2024-02-04 15:38:07 +0300 MSK
Partition Array for Maximum Sum
Links
Code
class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
min_num = -1
length = len(arr)
last_idx = length - 1
cache = [-1] * length
def dp(start: int) -> int:
cached = cache[start]
if cached != -1:
return cached
max_num = min_num
max_sum = 0
for i in range(start, min(start + k, length)):
max_num = max(max_num, arr[i])
cur_sum = max_num * (i - start + 1)
if i != last_idx:
cur_sum += dp(i + 1)
max_sum = max(max_sum, cur_sum)
cache[start] = max_sum
return max_sum
return dp(0)
867 - 2024-02-04 15:17:08 +0300 MSK
Minimum Window Substring
Links
Code
class Solution:
def minWindow(self, s: str, t: str) -> str:
if not s or not t:
return ""
dictT = defaultdict(int)
for c in t:
dictT[c] += 1
required = len(dictT)
l, r = 0, 0
formed = 0
windowCounts = defaultdict(int)
ans = [-1, 0, 0]
while r < len(s):
c = s[r]
windowCounts[c] += 1
if c in dictT and windowCounts[c] == dictT[c]:
formed += 1
while l <= r and formed == required:
c = s[l]
if ans[0] == -1 or r - l + 1 < ans[0]:
ans[0] = r - l + 1
ans[1] = l
ans[2] = r
windowCounts[c] -= 1
if c in dictT and windowCounts[c] < dictT[c]:
formed -= 1
l += 1
r += 1
return "" if ans[0] == -1 else s[ans[1]:ans[2] + 1]
868 - 2024-02-02 19:53:06 +0300 MSK
Divide Array Into Arrays With Max Difference
Links
Code
class Solution:
def divideArray(self, nums, k):
size = len(nums)
if size % 3 != 0:
return []
nums.sort()
result = []
group_index = 0
for i in range(0, size, 3):
if i + 2 < size and nums[i + 2] - nums[i] <= k:
result.append([nums[i], nums[i + 1], nums[i + 2]])
group_index += 1
else:
return []
return result
869 - 2024-02-02 19:52:11 +0300 MSK
Divide Array Into Arrays With Max Difference
Links
Code
class Solution:
def divideArray(self, nums, k):
size = len(nums)
if size % 3 != 0:
return []
nums.sort()
result = []
group_index = 0
for i in range(0, size, 3):
if i + 2 < size and nums[i + 2] - nums[i] <= k:
result.append([nums[i], nums[i + 1], nums[i + 2]])
group_index += 1
else:
return []
return result
870 - 2024-02-02 19:51:07 +0300 MSK
Sequential Digits
Links
Code
class Solution:
def sequentialDigits(self, low, high):
a = []
for i in range(1, 10):
num = i
next_digit = i + 1
while num <= high and next_digit <= 9:
num = num * 10 + next_digit
if low <= num <= high:
a.append(num)
next_digit += 1
a.sort()
return a
871 - 2024-01-31 11:09:51 +0300 MSK
Daily Temperatures
Links
Code
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
temps_left = defaultdict(list)
to_pop = []
length = len(temperatures)
ans = [0] * length
for i in range(length):
temp = temperatures[i]
for temp_left, ids in temps_left.items():
if temp <= temp_left:
continue
for id in ids:
ans[id] = i - id
to_pop.append(temp_left)
temps_left[temp].append(i)
for temp in to_pop:
temps_left.pop(temp)
to_pop.clear()
return ans
872 - 2024-01-30 15:36:53 +0300 MSK
Evaluate Reverse Polish Notation
Links
Code
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack: list[int] = []
for token in tokens:
match token:
case "+":
stack.append(stack.pop() + stack.pop())
case "-":
last, prev = stack.pop(), stack.pop()
stack.append(prev - last)
case "*":
stack.append(stack.pop() * stack.pop())
case "/":
last, prev = stack.pop(), stack.pop()
stack.append(int(prev / last))
case _:
stack.append(int(token))
return stack[0]
873 - 2024-01-29 09:44:33 +0300 MSK
Implement Queue using Stacks
Links
Code
class MyQueue:
def __init__(self):
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
self.stack_in.append(x)
def pop(self) -> int:
self.peek()
return self.stack_out.pop()
def peek(self) -> int:
if self.stack_out:
return self.stack_out[-1]
while self.stack_in:
self.stack_out.append(self.stack_in.pop())
return self.stack_out[-1]
def empty(self) -> bool:
return not self.stack_out and not self.stack_in
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
874 - 2024-01-28 13:34:03 +0300 MSK
Number of Submatrices That Sum to Target
Links
Code
class Solution:
def numSubmatrixSumTarget(self, matrix, target):
m, n = len(matrix), len(matrix[0])
for row in range(m):
for col in range(1, n):
matrix[row][col] += matrix[row][col - 1]
count = 0
for c1 in range(n):
for c2 in range(c1, n):
prefix_sum_count = {0: 1}
sum_val = 0
for row in range(m):
sum_val += matrix[row][c2] - (matrix[row][c1 - 1] if c1 > 0 else 0)
count += prefix_sum_count.get(sum_val - target, 0)
prefix_sum_count[sum_val] = prefix_sum_count.get(sum_val, 0) + 1
return count
875 - 2024-01-27 10:05:52 +0300 MSK
K Inverse Pairs Array
Links
Code
class Solution:
def kInversePairs(self, n: int, k: int) -> int:
MOD = 10**9 + 7
dp = [[0] * (k + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(k + 1):
if j == 0:
dp[i][j] = 1
else:
val = (dp[i - 1][j] + MOD - (dp[i - 1][j - i] if j - i >= 0 else 0)) % MOD
dp[i][j] = (dp[i][j - 1] + val) % MOD
return (dp[n][k] + MOD - (dp[n][k - 1] if k > 0 else 0)) % MOD
876 - 2024-01-26 11:02:15 +0300 MSK
Out of Boundary Paths
Links
Code
class Solution:
def findPaths(self, m: int, n: int, N: int, x: int, y: int) -> int:
M = 1000000000 + 7
dp = [[0] * n for _ in range(m)]
dp[x][y] = 1
count = 0
for moves in range(1, N + 1):
temp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == m - 1:
count = (count + dp[i][j]) % M
if j == n - 1:
count = (count + dp[i][j]) % M
if i == 0:
count = (count + dp[i][j]) % M
if j == 0:
count = (count + dp[i][j]) % M
temp[i][j] = (
((dp[i - 1][j] if i > 0 else 0) + (dp[i + 1][j] if i < m - 1 else 0)) % M +
((dp[i][j - 1] if j > 0 else 0) + (dp[i][j + 1] if j < n - 1 else 0)) % M
) % M
dp = temp
return count
877 - 2024-01-25 17:31:23 +0300 MSK
Longest Common Subsequence
Links
Code
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
# Get the lengths of both input strings
len_text1, len_text2 = len(text1), len(text2)
# Initialize a 2D array (list of lists) with zeros for dynamic programming
# The array has (len_text1 + 1) rows and (len_text2 + 1) columns
dp_matrix = [[0] * (len_text2 + 1) for _ in range(len_text1 + 1)]
# Loop through each character index of text1 and text2
for i in range(1, len_text1 + 1):
for j in range(1, len_text2 + 1):
# If the characters match, take the diagonal value and add 1
if text1[i - 1] == text2[j - 1]:
dp_matrix[i][j] = dp_matrix[i - 1][j - 1] + 1
else:
# If the characters do not match, take the maximum of the value from the left and above
dp_matrix[i][j] = max(dp_matrix[i - 1][j], dp_matrix[i][j - 1])
# The bottom-right value in the matrix contains the length of the longest common subsequence
return dp_matrix[len_text1][len_text2]
878 - 2024-01-24 10:39:27 +0300 MSK
Pseudo-Palindromic Paths in a Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:
if not root:
return 0
num_count = defaultdict(int)
perm_count = 0
def traverse(node: TreeNode) -> int:
val, left, right = node.val, node.left, node.right
num_count[val] += 1
res = 0
if not left and not right:
non_even = 0
for num in num_count.values():
if num % 2 == 0:
continue
if non_even == 1:
break
non_even += 1
else:
res += 1
if left:
res += traverse(left)
if right:
res += traverse(right)
num_count[val] = max(0, num_count[val] - 1)
return res
return traverse(root)
879 - 2024-01-24 10:27:08 +0300 MSK
Pseudo-Palindromic Paths in a Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:
if not root:
return 0
num_count = defaultdict(int)
perm_count = 0
def traverse(node: TreeNode) -> int:
if not node:
return 0
val, left, right = node.val, node.left, node.right
num_count[val] += 1
res = 0
if not left and not right:
non_even = 0
for num in num_count.values():
if num % 2 == 0:
continue
non_even += 1
if non_even > 1:
break
else:
res += 1
res += traverse(left) + traverse(right)
num_count[val] = max(0, num_count[val] - 1)
return res
return traverse(root)
880 - 2024-01-23 10:54:38 +0300 MSK
Maximum Length of a Concatenated String with Unique Characters
Links
Code
class Solution:
def maxLength(self, arr: List[str]) -> int:
cur = set()
length = len(arr)
max_length = 0
def backtrack(start: int) -> None:
nonlocal max_length
for i in range(start, length):
new_subs = arr[i]
new = set(new_subs)
if len(new_subs) != len(new) or len(cur.intersection(new)) != 0:
continue
cur.update(new)
backtrack(i + 1)
cur.difference_update(new)
max_length = max(max_length, len(cur))
backtrack(0)
return max_length
881 - 2024-01-22 12:39:06 +0300 MSK
Set Mismatch
Links
Code
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
length = len(nums)
# dupl_xor_miss = duplicate ^ missing
dupl_xor_miss = reduce(lambda total, i: total ^ i ^ nums[i - 1], range(length + 1))
rightmost_set_bit = dupl_xor_miss & -dupl_xor_miss
xor_group1 = xor_group2 = 0
for i in range(1, length + 1):
if i & rightmost_set_bit:
xor_group1 ^= i
else:
xor_group2 ^= i
if nums[i - 1] & rightmost_set_bit:
xor_group1 ^= nums[i - 1]
else:
xor_group2 ^= nums[i - 1]
for num in nums:
if num == xor_group1:
return num, xor_group2
if num == xor_group2:
return num, xor_group1
raise Exception()
882 - 2024-01-21 21:12:22 +0300 MSK
House Robber
Links
Code
class Solution:
def rob(self, nums: List[int]) -> int:
length = len(nums)
cache = {}
def dp(i: int) -> int:
if i >= length:
return 0
val = nums[i]
if i in cache:
return cache[i]
res = max(dp(i + 1), val + dp(i + 2))
cache[i] = res
return res
return dp(0)
883 - 2024-01-20 17:21:44 +0300 MSK
Sum of Subarray Minimums
Links
Code
class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
n = len(arr)
left = [-1] * n
right = [n] * n
stack = []
for i, value in enumerate(arr):
while stack and arr[stack[-1]] >= value:
stack.pop()
if stack:
left[i] = stack[-1]
stack.append(i)
stack = []
for i in range(n - 1, -1, -1):
while stack and arr[stack[-1]] > arr[i]:
stack.pop()
if stack:
right[i] = stack[-1]
stack.append(i)
mod = 10**9 + 7
result = sum((i - left[i]) * (right[i] - i) * value for i, value in enumerate(arr)) % mod
return result
884 - 2024-01-19 11:46:22 +0300 MSK
Minimum Falling Path Sum
Links
Code
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
length = len(matrix)
cache = {}
deltas = ((1, 0), (1, 1), (1, -1))
last_row = length - 1
def dp(row: int, col: int) -> int:
if (row, col) in cache:
return cache[(row, col)]
val = matrix[row][col]
if row == last_row:
return val
min_cost = None
for delta_row, delta_col in deltas:
new_row, new_col = row + delta_row, col + delta_col
if new_col == length or new_col == -1:
continue
cost = dp(new_row, new_col)
min_cost = cost if min_cost is None else min(min_cost, cost)
res = val + min_cost
cache[(row, col)] = res
return res
return min(dp(0, col) for col in range(length))
885 - 2024-01-19 11:45:33 +0300 MSK
Minimum Falling Path Sum
Links
Code
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
length = len(matrix)
max_val = 101 * length * length
cache = {}
deltas = ((1, 0), (1, 1), (1, -1))
last_row = length - 1
def dp(row: int, col: int) -> int:
if (row, col) in cache:
return cache[(row, col)]
val = matrix[row][col]
if row == last_row:
return val
min_cost = max_val
for delta_row, delta_col in deltas:
new_row, new_col = row + delta_row, col + delta_col
if new_col == length or new_col == -1:
continue
cost = dp(new_row, new_col)
min_cost = min(min_cost, cost)
res = val + min_cost
cache[(row, col)] = res
return res
return min(dp(0, col) for col in range(length))
886 - 2024-01-18 13:27:10 +0300 MSK
Climbing Stairs
Links
Code
class Solution:
def climbStairs(self, n: int) -> int:
prev, cur = 1, 2
if n == prev:
return prev
if n == cur:
return cur
for i in range(2, n):
new = prev + cur
cur, prev = new, cur
return cur
887 - 2024-01-17 19:14:04 +0300 MSK
Unique Number of Occurrences
Links
Code
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
counts = defaultdict(int)
for num in arr:
counts[num] += 1
viewed = set()
for _, count in counts.items():
if count in viewed:
return False
viewed.add(count)
return True
888 - 2024-01-16 11:04:01 +0300 MSK
Insert Delete GetRandom O(1)
Links
Code
import random
class RandomizedSet:
def __init__(self):
self._nums_map = {}
self._nums = []
def insert(self, val: int) -> bool:
if val in self._nums_map:
return False
self._nums_map[val] = len(self._nums)
self._nums.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self._nums_map:
return False
last = self._nums[-1]
idx = self._nums_map[val]
self._nums_map[last] = idx
self._nums[idx] = last
self._nums.pop()
self._nums_map.pop(val)
return True
def getRandom(self) -> int:
return random.choice(self._nums)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
889 - 2024-01-15 11:45:13 +0300 MSK
Find Players With Zero or One Losses
Links
Code
class Solution:
def findWinners(self, matches):
losses = [0] * 100001
for winner, loser in matches:
if losses[winner] == 0:
losses[winner] = -1
if losses[loser] == -1:
losses[loser] = 1
else:
losses[loser] += 1
zero_loss = [i for i in range(1, 100001) if losses[i] == -1]
one_loss = [i for i in range(1, 100001) if losses[i] == 1]
return [zero_loss, one_loss]
890 - 2024-01-14 17:27:29 +0300 MSK
Determine if Two Strings Are Close
Links
Code
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
freq1 = [0] * 26
freq2 = [0] * 26
for ch in word1:
freq1[ord(ch) - ord('a')] += 1
for ch in word2:
freq2[ord(ch) - ord('a')] += 1
for i in range(26):
if (freq1[i] == 0 and freq2[i] != 0) or (freq1[i] != 0 and freq2[i] == 0):
return False
freq1.sort()
freq2.sort()
for i in range(26):
if freq1[i] != freq2[i]:
return False
return True
891 - 2024-01-13 17:33:48 +0300 MSK
Minimum Number of Steps to Make Two Strings Anagram
Links
Code
class Solution:
def minSteps(self, s: str, t: str) -> int:
count_s = [0] * 26
count_t = [0] * 26
for char in s:
count_s[ord(char) - ord('a')] += 1
for char in t:
count_t[ord(char) - ord('a')] += 1
steps = 0
for i in range(26):
steps += abs(count_s[i] - count_t[i])
return steps // 2
892 - 2024-01-12 23:55:40 +0300 MSK
Determine if String Halves Are Alike
Links
Code
class Solution:
def halvesAreAlike(self, s: str) -> bool:
def count_vowels(string):
vowels = set('aeiouAEIOU')
return sum(1 for char in string if char in vowels)
length = len(s)
mid_point = length // 2
first_half = s[:mid_point]
second_half = s[mid_point:]
return count_vowels(first_half) == count_vowels(second_half)
893 - 2024-01-11 12:15:51 +0300 MSK
Maximum Difference Between Node and Ancestor
Links
Code
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def maxAncestorDiff(self, root):
if not root:
return 0
self.diff = 0
self.helper(root, root.val, root.val)
return self.diff
def helper(self, root, min_val, max_val):
if not root:
return
self.diff = max(self.diff, max(abs(min_val - root.val), abs(max_val - root.val)))
min_val = min(min_val, root.val)
max_val = max(max_val, root.val)
self.helper(root.left, min_val, max_val)
self.helper(root.right, min_val, max_val)
894 - 2024-01-10 11:34:26 +0300 MSK
Amount of Time for Binary Tree to Be Infected
Links
Code
class Solution:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
def dfs(node):
if node is None:
return
if node.left:
graph[node.val].append(node.left.val)
graph[node.left.val].append(node.val)
if node.right:
graph[node.val].append(node.right.val)
graph[node.right.val].append(node.val)
dfs(node.left)
dfs(node.right)
graph = defaultdict(list)
dfs(root)
visited = set()
queue = deque([start])
time = -1
while queue:
time += 1
for _ in range(len(queue)):
current_node = queue.popleft()
visited.add(current_node)
for neighbor in graph[current_node]:
if neighbor not in visited:
queue.append(neighbor)
return time
895 - 2024-01-09 19:45:41 +0300 MSK
Leaf-Similar Trees
Links
Code
class Solution:
def leafSimilar(self, root1, root2):
def dfs(node):
if node:
if not node.left and not node.right:
yield node.val
yield from dfs(node.left)
yield from dfs(node.right)
return list(dfs(root1)) == list(dfs(root2))
896 - 2024-01-08 17:44:21 +0300 MSK
Range Sum of BST
Links
Code
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
def dfs(node):
if not node:
return 0
current_val = 0
if low <= node.val <= high:
current_val = node.val
left_sum = dfs(node.left)
right_sum = dfs(node.right)
return current_val + left_sum + right_sum
return dfs(root)
897 - 2024-01-07 12:26:09 +0300 MSK
Maximum Profit in Job Scheduling
Links
Code
class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
jobs = sorted(zip(endTime, startTime, profit))
number_of_jobs = len(profit)
dp = [0] * (number_of_jobs + 1)
for i, (current_end_time, current_start_time, current_profit) in enumerate(jobs):
index = bisect_right(jobs, current_start_time, hi=i, key=lambda x: x[0])
dp[i + 1] = max(dp[i], dp[index] + current_profit)
return dp[number_of_jobs]
898 - 2024-01-07 12:23:04 +0300 MSK
Arithmetic Slices II - Subsequence
Links
Code
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
n = len(nums)
total_count = 0
dp = [defaultdict(int) for _ in range(n)]
for i in range(1, n):
for j in range(i):
diff = nums[i] - nums[j]
dp[i][diff] += 1
if diff in dp[j]:
dp[i][diff] += dp[j][diff]
total_count += dp[j][diff]
return total_count
899 - 2024-01-05 13:00:49 +0300 MSK
Longest Increasing Subsequence
Links
Code
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
if not nums:
return 0
n = len(nums)
dp = [1] * n
for i in range(1, n):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
900 - 2024-01-04 14:11:50 +0300 MSK
Minimum Number of Operations to Make Array Empty
Links
Code
class Solution:
def minOperations(self, nums: List[int]) -> int:
counter = Counter(nums)
ans = 0
for c in counter.values():
if c == 1:
return -1
ans += ceil(c / 3)
return ans
901 - 2024-01-03 14:46:50 +0300 MSK
Number of Laser Beams in a Bank
Links
Code
class Solution:
def numberOfBeams(self, bank):
ans, temp = 0, 0
for s in bank:
n = s.count('1')
if n == 0:
continue
ans += temp * n
temp = n
return ans
902 - 2024-01-02 15:20:19 +0300 MSK
Convert an Array Into a 2D Array With Conditions
Links
Code
class Solution:
def findMatrix(self, v: List[int]) -> List[List[int]]:
um = {}
for i in v:
um[i] = um.get(i, 0) + 1
ans = []
while um:
temp = []
to_erase = []
for f, s in um.items():
temp.append(f)
s -= 1
if s == 0:
to_erase.append(f)
um[f] = s
ans.append(temp)
for i in to_erase:
del um[i]
return ans
903 - 2024-01-01 16:10:42 +0300 MSK
Assign Cookies
Links
Code
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
content_children = 0
cookie_index = 0
while cookie_index < len(s) and content_children < len(g):
if s[cookie_index] >= g[content_children]:
content_children += 1
cookie_index += 1
return content_children
904 - 2023-12-31 13:19:35 +0300 MSK
Largest Substring Between Two Equal Characters
Links
Code
class Solution:
def maxLengthBetweenEqualCharacters(self, s: str) -> int:
ans = -1
for left in range(len(s)):
for right in range(left + 1, len(s)):
if s[left] == s[right]:
ans = max(ans, right - left - 1)
return ans
905 - 2023-12-30 14:22:38 +0300 MSK
Redistribute Characters to Make All Strings Equal
Links
Code
class Solution:
def makeEqual(self, words: List[str]) -> bool:
counts = defaultdict(int)
for word in words:
for c in word:
counts[c] += 1
n = len(words)
for val in counts.values():
if val % n != 0:
return False
return True
906 - 2023-12-29 10:09:26 +0300 MSK
Minimum Difficulty of a Job Schedule
Links
Code
class Solution:
def minDifficulty(self, jobDifficulty, days):
length = len(jobDifficulty)
if days > length:
return -1
min_difficulties = [[float('inf')] * length for _ in range(days)]
max_diff = 0
i = 0
while i <= length - days:
max_diff = max(max_diff, jobDifficulty[i])
min_difficulties[0][i] = max_diff
i += 1
current_day = 1
while current_day < days:
to = current_day
while to <= length - days + current_day:
current_job_difficulty = jobDifficulty[to]
result = float('inf')
j = to - 1
while j >= current_day - 1:
result = min(result, min_difficulties[current_day - 1][j] + current_job_difficulty)
current_job_difficulty = max(current_job_difficulty, jobDifficulty[j])
j -= 1
min_difficulties[current_day][to] = result
to += 1
current_day += 1
return min_difficulties[days - 1][length - 1]
907 - 2023-12-28 10:12:36 +0300 MSK
String Compression II
Links
Code
class Solution:
def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
n = len(s)
dp = [[9999] * 110 for _ in range(110)]
dp[0][0] = 0
for i in range(1, n + 1):
for j in range(0, k + 1):
cnt, del_ = 0, 0
for l in range(i, 0, -1):
if s[l - 1] == s[i - 1]:
cnt += 1
else:
del_ += 1
if j - del_ >= 0:
dp[i][j] = min(dp[i][j], dp[l - 1][j - del_] + 1 + (3 if cnt >= 100 else 2 if cnt >= 10 else 1 if cnt >= 2 else 0))
if j > 0:
dp[i][j] = min(dp[i][j], dp[i - 1][j - 1])
return dp[n][k]
908 - 2023-12-27 11:51:17 +0300 MSK
Minimum Time to Make Rope Colorful
Links
Code
class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
totalTime = 0
i = 0
j = 0
while i < len(neededTime) and j < len(neededTime):
currTotal = 0
currMax = 0
while j < len(neededTime) and colors[i] == colors[j]:
currTotal += neededTime[j]
currMax = max(currMax, neededTime[j])
j += 1
totalTime += currTotal - currMax
i = j
return totalTime
909 - 2023-12-26 11:08:25 +0300 MSK
Number of Dice Rolls With Target Sum
Links
Code
class Solution:
mod = 10 ** 9 + 7
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
dp = [[-1] * (target + 1) for _ in range(n + 1)]
return self.recursion(dp, n, k, target)
def recursion(self, dp: list, n: int, k: int, target: int) -> int:
if target == 0 and n == 0:
return 1
if n == 0 or target <= 0:
return 0
if dp[n][target] != -1:
return dp[n][target] % self.mod
ways = 0
for i in range(1, k + 1):
ways = (ways + self.recursion(dp, n - 1, k, target - i)) % self.mod
dp[n][target] = ways % self.mod
return dp[n][target]
910 - 2023-12-25 10:53:55 +0300 MSK
Decode Ways
Links
Code
class Solution:
def numDecodings(self, s):
if s == "0":
return 0
# dp_0 = dp[i]
# dp_1 = dp[i + 1]
# dp_2 = dp[i + 2]
dp_2 = 1
dp_1 = int(s[-1] != "0")
i = len(s) - 2
while i >= 0:
if s[i] == "0":
dp_0 = 0
else:
dp_0 = dp_1
if (s[i] == "1") or (s[i] == "2" and eval(s[i + 1]) < 7):
dp_0 += dp_2
i -= 1
dp_0, dp_1, dp_2 = 0, dp_0, dp_1
return dp_1
911 - 2023-12-24 12:54:15 +0300 MSK
Minimum Changes To Make Alternating Binary String
Links
Code
class Solution:
def minOperations(self, s: str) -> int:
start0 = 0
start1 = 0
for i in range(len(s)):
if i % 2 == 0:
if s[i] == "0":
start1 += 1
else:
start0 += 1
else:
if s[i] == "1":
start1 += 1
else:
start0 += 1
return min(start0, start1)
912 - 2023-12-24 00:41:36 +0300 MSK
Path Crossing
Links
Code
class Solution:
def isPathCrossing(self, path: str) -> bool:
moves = {
"N": (0, 1),
"S": (0, -1),
"W": (-1, 0),
"E": (1, 0)
}
visited = {(0, 0)}
x = 0
y = 0
for c in path:
dx, dy = moves[c]
x += dx
y += dy
if (x, y) in visited:
return True
visited.add((x, y))
return False
913 - 2023-12-22 11:52:14 +0300 MSK
Maximum Score After Splitting a String
Links
Code
class Solution:
def maxScore(self, s: str) -> int:
ones = s.count("1")
zeros = 0
ans = 0
for i in range(len(s) - 1):
if s[i] == "1":
ones -= 1
else:
zeros += 1
ans = max(ans, zeros + ones)
return ans
914 - 2023-12-21 08:42:34 +0300 MSK
Widest Vertical Area Between Two Points Containing No Points
Links
Code
class Solution:
def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
points.sort(key=lambda x: x[0])
max_width = 0
for i in range(1, len(points)):
width = points[i][0] - points[i-1][0]
max_width = max(max_width, width)
return max_width
915 - 2023-12-20 14:05:16 +0300 MSK
Buy Two Chocolates
Links
Code
class Solution:
def buyChoco(self, prices: List[int], money: int) -> int:
# Assume the Minimum Cost to be Infinity
min_cost = float('inf')
# Number of Chocolates
n = len(prices)
# Check Every Pair of Chocolates
for first_choco in range(n):
for second_choco in range(first_choco + 1, n):
# Sum of Prices of the Two Chocolates
cost = prices[first_choco] + prices[second_choco]
# If the Sum of Prices is Less than the Minimum Cost
if cost < min_cost:
# Update the Minimum Cost
min_cost = cost
# We can buy chocolates only if we have enough money
if min_cost <= money:
# Return the Amount of Money Left
return money - min_cost
else:
# We cannot buy chocolates. Return the initial amount of money
return money
916 - 2023-12-19 11:24:47 +0300 MSK
Image Smoother
Links
Code
class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
# Save the dimensions of the image.
m = len(img)
n = len(img[0])
# Create a new image of the same dimension as the input image.
smooth_img = [[0] * n for _ in range(m)]
# Iterate over the cells of the image.
for i in range(m):
for j in range(n):
# Initialize the sum and count
sum = 0
count = 0
# Iterate over all plausible nine indices.
for x in (i - 1, i, i + 1):
for y in (j - 1, j, j + 1):
# If the indices form valid neighbor
if 0 <= x < m and 0 <= y < n:
sum += img[x][y]
count += 1
# Store the rounded down value in smooth_img[i][j].
smooth_img[i][j] = sum // count
# Return the smooth image.
return smooth_img
917 - 2023-12-18 13:27:09 +0300 MSK
Maximum Product Difference Between Two Pairs
Links
Code
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return nums[-1] * nums[-2] - nums[0] * nums[1]
918 - 2023-12-17 12:09:37 +0300 MSK
Design a Food Rating System
Links
Code
class Food:
def __init__(self, food_rating, food_name):
# Store the food's rating.
self.food_rating = food_rating
# Store the food's name.
self.food_name = food_name
def __lt__(self, other):
# Overload the less than operator for comparison.
# If food ratings are the same, sort based on their name (lexicographically smaller name food will be on top).
if self.food_rating == other.food_rating:
return self.food_name < other.food_name
# Sort based on food rating (bigger rating food will be on top).
return self.food_rating > other.food_rating
class FoodRatings:
def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
# Map food with its rating.
self.food_rating_map = {}
# Map food with the cuisine it belongs to.
self.food_cuisine_map = {}
# Store all food of a cuisine in a priority queue (to sort them on ratings/name).
# Priority queue element -> Food: (food_rating, food_name)
self.cuisine_food_map = defaultdict(list)
for i in range(len(foods)):
# Store 'rating' and 'cuisine' of the current 'food' in 'food_rating_map' and 'food_cuisine_map' maps.
self.food_rating_map[foods[i]] = ratings[i]
self.food_cuisine_map[foods[i]] = cuisines[i]
# Insert the '(rating, name)' element into the current cuisine's priority queue.
heapq.heappush(self.cuisine_food_map[cuisines[i]], Food(ratings[i], foods[i]))
def changeRating(self, food: str, newRating: int) -> None:
# Update food's rating in 'food_rating' map.
self.food_rating_map[food] = newRating
# Insert the '(new rating, name)' element in the respective cuisine's priority queue.
cuisineName = self.food_cuisine_map[food]
heapq.heappush(self.cuisine_food_map[cuisineName], Food(newRating, food))
def highestRated(self, cuisine: str) -> str:
# Get the highest rated 'food' of 'cuisine'.
highest_rated = self.cuisine_food_map[cuisine][0]
# If the latest rating of 'food' doesn't match with the 'rating' on which it was sorted in the priority queue,
# then we discard this element from the priority queue.
while self.food_rating_map[highest_rated.food_name] != highest_rated.food_rating:
heapq.heappop(self.cuisine_food_map[cuisine])
highest_rated = self.cuisine_food_map[cuisine][0]
# Return the name of the highest-rated 'food' of 'cuisine'.
return highest_rated.food_name
919 - 2023-12-16 13:01:55 +0300 MSK
Valid Anagram
Links
Code
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if (len(s) != len(t)):
return False
letters = [0] * 26
for char in s:
letters[ord(char) - ord('a')] += 1
for char in t:
i = ord(char) - ord('a')
letters[i] -= 1
if letters[i] < 0:
return False
return True
920 - 2023-12-15 10:56:18 +0300 MSK
Destination City
Links
Code
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
paths_from = set()
for path_from, path_to in paths:
paths_from.add(path_from)
ans = ""
for _, path_to in paths:
if path_to not in paths_from:
ans = path_to
break
return ans
921 - 2023-12-15 10:54:52 +0300 MSK
Destination City
Links
Code
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
paths_from, paths_to = set(), set()
for path_from, path_to in paths:
paths_from.add(path_from)
paths_to.add(path_to)
return (paths_to - paths_from).pop()
922 - 2023-12-14 12:30:55 +0300 MSK
Difference Between Ones and Zeros in Row and Column
Links
Code
class Solution:
def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]:
m = len(grid)
n = len(grid[0])
rows = {}
for r in range(m):
row_sum = 0
for c in range(n):
row_sum += grid[r][c]
rows[r] = row_sum
cols = {}
for c in range(n):
col_sum = 0
for r in range(m):
col_sum += grid[r][c]
cols[c] = col_sum
res = [[0] * n for _ in range(m)]
for r in range(m):
for c in range(n):
res[r][c] = rows[r] + cols[c] - (m - rows[r]) - (n - cols[c])
return res
923 - 2023-12-13 11:11:00 +0300 MSK
Special Positions in a Binary Matrix
Links
Code
class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
def get_column_sum(col_idx):
return sum(row[col_idx] for row in mat)
special = 0
for row in mat:
if sum(row) == 1:
col_idx = row.index(1)
special += get_column_sum(col_idx) == 1
return special
924 - 2023-12-12 10:39:45 +0300 MSK
Maximum Product of Two Elements in an Array
Links
Code
class Solution:
def maxProduct(self, nums: List[int]) -> int:
biggest = 0
second_biggest = 0
for num in nums:
if num > biggest:
second_biggest = biggest
biggest = num
else:
second_biggest = max(second_biggest, num)
return (biggest - 1) * (second_biggest - 1)
925 - 2023-12-11 15:30:35 +0300 MSK
Keyboard Row
Links
Code
class Solution:
def findWords(self, words: List[str]) -> List[str]:
ans = []
rows = [
set("qwertyuiop"),
set("asdfghjkl"),
set("zxcvbnm")
]
for word in words:
for row in rows:
if len(row.union(word.lower())) == len(row):
ans.append(word)
break
return ans
926 - 2023-12-11 10:26:55 +0300 MSK
Element Appearing More Than 25% In Sorted Array
Links
Code
class Solution:
def findSpecialInteger(self, arr: List[int]) -> int:
prev, count = arr[0], 1
quarter = len(arr) / 4
for num in arr[1:]:
if num == prev:
count += 1
else:
prev = num
count = 1
if count > quarter:
break
return prev
927 - 2023-12-10 13:46:54 +0300 MSK
Binary Tree Inorder Traversal
Links
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
helper(root, result);
return result;
}
void helper(TreeNode* root, vector<int>& result) {
if (root != nullptr) {
helper(root->left, result);
result.push_back(root->val);
helper(root->right, result);
}
}
};
928 - 2023-12-10 13:46:22 +0300 MSK
Binary Tree Inorder Traversal
Links
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
helper(root, result);
return result;
}
void helper(TreeNode* root, vector<int>& result) {
if (root != nullptr) {
helper(root->left, result);
result.push_back(root->val);
helper(root->right, result);
}
}
};
929 - 2023-12-10 13:45:46 +0300 MSK
Transpose Matrix
Links
Code
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
int row = matrix.size();
int col = matrix[0].size();
vector<vector<int>> result(col, vector<int>(row, 0));
for (int i = 0; i < col; ++i) {
for (int j = 0; j < row; ++j) {
result[i][j] = matrix[j][i];
}
}
return result;
}
};
930 - 2023-12-08 21:03:57 +0300 MSK
Construct String from Binary Tree
Links
Code
class Solution {
public:
string tree2str(TreeNode* root) {
string str = "";
check(root, str);
return str;
}
void check(TreeNode* root, string &str) {
if (root == NULL) {
return;
}
str += to_string(root->val);
if (root->left || root->right) {
str += '(';
check(root->left, str);
str += ')';
}
if (root->right) {
str += '(';
check(root->right, str);
str += ')';
}
}
};
931 - 2023-12-07 19:20:48 +0300 MSK
Largest Odd Number in String
Links
Code
class Solution {
public:
string largestOddNumber(string num) {
size_t length {num.size()};
for (int i = length - 1; i >= 0; --i) {
if ((num[i] - '0') % 2 != 0) {
return num.substr(0, i + 1);
}
}
return "";
}
};
932 - 2023-12-06 12:45:40 +0300 MSK
Palindrome Linked List
Links
Code
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode* slow {head};
ListNode* fast {head};
ListNode* next;
ListNode* prev {new ListNode()};
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
next = head->next;
head->next = prev;
prev = head;
head = next;
}
if (fast) {
slow = slow->next;
}
head = prev;
while (slow) {
if (head->val != slow->val) {
return false;
}
head = head->next;
slow = slow->next;
}
return true;
}
};
933 - 2023-12-06 09:43:04 +0300 MSK
Calculate Money in Leetcode Bank
Links
Code
class Solution {
public:
int totalMoney(int n) {
int ans {0};
int monday {1};
while (n > 0) {
for (int day {0}; day < min(n, 7); ++day) {
ans += monday + day;
}
n -= 7;
++monday;
}
return ans;
}
};
934 - 2023-12-05 16:12:24 +0300 MSK
Count of Matches in Tournament
Links
Code
class Solution {
public:
int numberOfMatches(int n) {
int ans = 0;
while (n > 1) {
if (n % 2 == 0) {
int matches {n / 2};
ans += matches;
n = matches;
} else {
int matches {(n - 1) / 2};
ans += matches;
n = matches + 1;
}
}
return ans;
}
};
935 - 2023-12-04 11:09:00 +0300 MSK
Largest 3-Same-Digit Number in String
Links
Code
class Solution {
public:
string largestGoodInteger(string num) {
int cur {-1};
int max {-1};
int count {0};
for (const char& ch : num) {
int i {ch - '0'};
if (i == cur) {
++count;
} else {
cur = i;
count = 1;
}
if (count == 3) {
max = std::max(i, max);
}
}
if (max == -1) {
return "";
}
std::string ans {std::to_string(max)};
return ans + ans + ans;
}
};
936 - 2023-12-03 17:53:13 +0300 MSK
Minimum Time Visiting All Points
Links
Code
class Solution {
public:
int minTimeToVisitAllPoints(vector<vector<int>>& points) {
int ans = 0;
for (int i = 0; i < points.size() - 1; i++) {
int currX = points[i][0];
int currY = points[i][1];
int targetX = points[i + 1][0];
int targetY = points[i + 1][1];
ans += max(abs(targetX - currX), abs(targetY - currY));
}
return ans;
}
};
937 - 2023-12-02 23:40:09 +0300 MSK
Find Words That Can Be Formed by Characters
Links
Code
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
std::vector<int> count {};
int ans {};
count.resize(26);
for (const char& ch : chars) {
++count[ch - 'a'];
}
for (const string& word : words) {
std::vector<int> wordCount {};
wordCount.resize(26);
bool failure {false};
for (const char& ch : word) {
int i {ch - 'a'};
int cur {++wordCount[i]};
if (cur > count[i]) {
failure = true;
break;
}
}
if (!failure) {
ans += word.length();
}
}
return ans;
}
};
938 - 2023-12-01 11:21:29 +0300 MSK
Check If Two String Arrays are Equivalent
Links
Code
class Solution {
public:
bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
string s1 = "";
string s2 = "";
for(const string& s : word1) {
s1 += s;
}
for(const string& s : word2) {
s2 += s;
}
return s1==s2;
}
};
939 - 2023-11-30 10:50:12 +0300 MSK
Minimum One Bit Operations to Make Integers Zero
Links
Code
class Solution {
public:
int minimumOneBitOperations(int n) {
if (n == 0) {
return 0;
}
int k = 0;
int curr = 1;
while (curr * 2 <= n) {
curr *= 2;
k++;
}
return (1 << (k + 1)) - 1 - minimumOneBitOperations(n ^ curr);
}
};
940 - 2023-11-29 12:01:45 +0300 MSK
Number of 1 Bits
Links
Code
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans {};
while (n) {
if (n & 1) {
++ans;
}
n >>= 1;
}
return ans;
}
};
941 - 2023-11-28 13:04:41 +0300 MSK
Number of Ways to Divide a Long Corridor
Links
Code
class Solution {
public:
// Store 1000000007 in a variable for convenience
const int MOD = 1e9 + 7;
// Count the number of ways to divide from "index" to the last index
// with "seats" number of "S" in the current section
int count(int index, int seats, string& corridor, int cache[][3]) {
// If we have reached the end of the corridor, then
// the current section is valid only if "seats" is 2
if (index == corridor.length()) {
return seats == 2 ? 1 : 0;
}
// If we have already computed the result of this sub-problem,
// then return the cached result
if (cache[index][seats] != -1) {
return cache[index][seats];
}
// Result of the sub-problem
int result = 0;
// If the current section has exactly 2 "S"
if (seats == 2) {
// If the current element is "S", then we have to close the
// section and start a new section from this index. Next index
// will have one "S" in the current section
if (corridor[index] == 'S') {
result = count(index + 1, 1, corridor, cache);
} else {
// If the current element is "P", then we have two options
// 1. Close the section and start a new section from this index
// 2. Keep growing the section
result = (count(index + 1, 0, corridor, cache) + count(index + 1, 2, corridor, cache)) % MOD;
}
} else {
// Keep growing the section. Increment "seats" if present
// element is "S"
if (corridor[index] == 'S') {
result = count(index + 1, seats + 1, corridor, cache);
} else {
result = count(index + 1, seats, corridor, cache);
}
}
// Memoize the result, and return it
cache[index][seats] = result;
return cache[index][seats];
}
int numberOfWays(string corridor) {
// Cache the result of each sub-problem
int cache[corridor.length()][3];
memset(cache, -1, sizeof(cache));
// Call the count function
return count(0, 0, corridor, cache);
}
};
942 - 2023-11-27 10:32:44 +0300 MSK
Largest Submatrix With Rearrangements
Links
Code
class Solution {
public:
int largestSubmatrix(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
int ans = 0;
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
if (matrix[row][col] != 0 && row > 0) {
matrix[row][col] += matrix[row - 1][col];
}
}
vector<int> currRow = matrix[row];
sort(currRow.begin(), currRow.end(), greater());
for (int i = 0; i < n; i++) {
ans = max(ans, currRow[i] * (i + 1));
}
}
return ans;
}
};
943 - 2023-11-27 10:32:13 +0300 MSK
Knight Dialer
Links
Code
class Solution {
public:
vector<vector<int>> memo;
int n;
int MOD = 1e9 + 7;
vector<vector<int>> jumps = {
{4, 6},
{6, 8},
{7, 9},
{4, 8},
{3, 9, 0},
{},
{1, 7, 0},
{2, 6},
{1, 3},
{2, 4}
};
int dp(int remain, int square) {
if (remain == 0) {
return 1;
}
if (memo[remain][square] != 0) {
return memo[remain][square];
}
int ans = 0;
for (int nextSquare : jumps[square]) {
ans = (ans + dp(remain - 1, nextSquare)) % MOD;
}
memo[remain][square] = ans;
return ans;
}
int knightDialer(int n) {
this->n = n;
memo = vector(n + 1, vector(10, 0));
int ans = 0;
for (int square = 0; square < 10; square++) {
ans = (ans + dp(n - 1, square)) % MOD;
}
return ans;
}
};
944 - 2023-11-25 22:00:45 +0300 MSK
Sum of Absolute Differences in a Sorted Array
Links
Code
class Solution {
public:
vector<int> getSumAbsoluteDifferences(vector<int>& nums) {
int n = nums.size();
int totalSum = accumulate(nums.begin(), nums.end(), 0);
int leftSum = 0;
vector<int> ans;
for (int i = 0; i < n; i++) {
int rightSum = totalSum - leftSum - nums[i];
int leftCount = i;
int rightCount = n - 1 - i;
int leftTotal = leftCount * nums[i] - leftSum;
int rightTotal = rightSum - rightCount * nums[i];
ans.push_back(leftTotal + rightTotal);
leftSum += nums[i];
}
return ans;
}
};
945 - 2023-11-25 22:00:22 +0300 MSK
Sum of Absolute Differences in a Sorted Array
Links
Code
class Solution {
public:
vector<int> getSumAbsoluteDifferences(vector<int>& nums) {
int n = nums.size();
vector<int> prefix = {nums[0]};
for (int i = 1; i < n; i++) {
prefix.push_back(prefix[i - 1] + nums[i]);
}
vector<int> ans;
for (int i = 0; i < n; i++) {
int leftSum = prefix[i] - nums[i];
int rightSum = prefix[n - 1] - prefix[i];
int leftCount = i;
int rightCount = n - 1 - i;
int leftTotal = leftCount * nums[i] - leftSum;
int rightTotal = rightSum - rightCount * nums[i];
ans.push_back(leftTotal + rightTotal);
}
return ans;
}
};
946 - 2023-11-24 16:49:32 +0300 MSK
Kids With the Greatest Number of Candies
Links
Code
class Solution {
public:
std::vector<bool> kidsWithCandies(std::vector<int>& candies, int extraCandies) {
size_t length {candies.size()};
std::vector<bool> ans {};
ans.resize(length);
const int maxCandy {*std::max_element(candies.begin(), candies.end())};
for (size_t i = 0; i < length; ++i) {
ans[i] = (candies[i] + extraCandies) >= maxCandy;
}
return ans;
}
};
947 - 2023-11-24 16:37:41 +0300 MSK
Greatest Common Divisor of Strings
Links
Code
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
if (str1 + str2 == str2 + str1) {
return str1.substr(0, std::gcd(str1.size(), str2.size()));
}
return "";
}
};
948 - 2023-11-24 16:36:38 +0300 MSK
Greatest Common Divisor of Strings
Links
Code
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
if (str1 + str2 != str2 + str1) {
return "";
}
unsigned long gcdLength {std::gcd(str1.size(), str2.size())};
return str1.substr(0, gcdLength);
}
};
949 - 2023-11-24 16:32:52 +0300 MSK
Greatest Common Divisor of Strings
Links
Code
class Solution {
public:
bool valid(string str1, string str2, size_t k) {
size_t len1 {str1.size()}, len2 {str2.size()};
if (len1 % k != 0 || len2 % k != 0) {
return false;
}
string base = str1.substr(0, k);
size_t n1 {len1 / k}, n2 {len2 / k};
if (n1 == n2) {
return str1 == str2 && joinWords(base, n1) == str1;
}
return str1 == joinWords(base, n1) && str2 == joinWords(base, n2);
}
string joinWords(string str, size_t k) {
string ans = "";
for (size_t i = 0; i < k; ++i) {
ans += str;
}
return ans;
}
string gcdOfStrings(string str1, string str2) {
for (size_t i = min(str1.size(), str2.size()); i > 0; --i) {
if (valid(str1, str2, i)) {
return str1.substr(0, i);
}
}
return "";
}
};
950 - 2023-11-24 11:07:37 +0300 MSK
Maximum Number of Coins You Can Get
Links
Code
class Solution {
public:
int maxCoins(vector<int>& piles) {
std::sort(piles.begin(), piles.end());
size_t length {piles.size()};
size_t picks {length / 3};
int count {};
for (size_t i {length - 2}; picks > 0; i -= 2, --picks) {
count += piles[i];
}
return count;
}
};
951 - 2023-11-23 13:41:25 +0300 MSK
Arithmetic Subarrays
Links
Code
class Solution {
public:
bool check(vector<int>& arr) {
sort(arr.begin(), arr.end());
int diff = arr[1] - arr[0];
for (int i = 2; i < arr.size(); i++) {
if (arr[i] - arr[i - 1] != diff) {
return false;
}
}
return true;
}
vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) {
vector<bool> ans;
for (int i = 0; i < l.size(); i++) {
vector<int> arr(begin(nums) + l[i], begin(nums) + r[i] + 1);
ans.push_back(check(arr));
}
return ans;
}
};
952 - 2023-11-22 18:49:02 +0300 MSK
Diagonal Traverse II
Links
Code
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
unordered_map<int, vector<int>> groups;
for (int row = nums.size() - 1; row >= 0; row--) {
for (int col = 0; col < nums[row].size(); col++) {
int diagonal = row + col;
groups[diagonal].push_back(nums[row][col]);
}
}
vector<int> ans;
int curr = 0;
while (groups.find(curr) != groups.end()) {
for (int num : groups[curr]) {
ans.push_back(num);
}
curr++;
}
return ans;
}
};
953 - 2023-11-21 12:51:21 +0300 MSK
Binary Tree Paths
Links
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
dfs(*root, ans, "");
return ans;
}
void dfs(TreeNode& root, vector<string> &ans, string path){
path += (path.size() ? "->" : "") + std::to_string(root.val);
if(!root.left && !root.right) {
ans.push_back(path);
return;
}
if(root.left) {
dfs(*root.left, ans, path);
}
if(root.right) {
dfs(*root.right, ans, path);
}
}
};
954 - 2023-11-21 12:44:04 +0300 MSK
Count Nice Pairs in an Array
Links
Code
class Solution {
public:
int countNicePairs(vector<int>& nums) {
std::unordered_map<int, int> diffs{};
int ans{};
double mod{1e9 + 7};
for (const int& num : nums) {
int revNum{};
int tempNum{num};
while(tempNum) {
revNum = (revNum * 10) + (tempNum % 10);
tempNum /= 10;
}
int diff{num-revNum};
if (diffs.contains(diff)) {
ans = std::fmod(ans + diffs[diff], mod);
}
++diffs[diff];
}
return ans;
}
};
955 - 2023-11-21 12:33:13 +0300 MSK
Count Nice Pairs in an Array
Links
Code
class Solution {
public:
int countNicePairs(vector<int>& nums) {
std::unordered_map<int, int> diffs{};
for (const int& num : nums) {
int revNum{};
int tempNum{num};
while(tempNum) {
revNum = (revNum * 10) + (tempNum % 10);
tempNum /= 10;
}
++diffs[num - revNum];
}
int ans{};
double mod{std::pow(10, 9) + 7};
for (const auto& [num, count] : diffs) {
long pairs{(1L * count * count - count) / 2};
ans = std::fmod(ans + pairs, mod);
}
return ans;
}
};
956 - 2023-11-20 18:30:57 +0300 MSK
Excel Sheet Column Number
Links
Code
class Solution {
public:
int titleToNumber(string columnTitle) {
int ans{0};
for (const char& ch : columnTitle) {
ans = (ans * 26) + (ch - 'A') + 1;
}
return ans;
}
};
957 - 2023-11-20 14:40:36 +0300 MSK
Binary Tree Postorder Traversal
Links
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if (root == nullptr) {
return {};
}
std::vector<int> ans{};
addNodes(*root, ans);
return ans;
}
void addNodes(TreeNode& node, std::vector<int>& ans) {
if (node.left != nullptr) {
addNodes(*node.left, ans);
}
if (node.right != nullptr) {
addNodes(*node.right, ans);
}
ans.push_back(node.val);
}
};
958 - 2023-11-20 14:38:40 +0300 MSK
Binary Tree Postorder Traversal
Links
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if (root == nullptr) {
return {};
}
std::vector<int> ans{};
addNodes(root, ans);
return ans;
}
void addNodes(TreeNode* node, std::vector<int>& ans) {
auto left{node->left}, right{node->right};
if (left != nullptr) {
addNodes(left, ans);
}
if (right != nullptr) {
addNodes(right, ans);
}
ans.push_back(node->val);
}
};
959 - 2023-11-20 14:31:25 +0300 MSK
Binary Tree Preorder Traversal
Links
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if (root == nullptr) {
return {};
}
std::vector<int> ans{};
std::vector<TreeNode*> q{root};
while (q.size() != 0) {
auto node = q.back();
auto left{node->left}, right{node->right};
q.pop_back();
ans.push_back(node->val);
if (right != nullptr) {
q.push_back(right);
}
if (left != nullptr) {
q.push_back(left);
}
}
return ans;
}
};
960 - 2023-11-20 14:29:40 +0300 MSK
Binary Tree Preorder Traversal
Links
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if (root == nullptr) {
return {};
}
std::vector<int> ans{};
std::deque<TreeNode*> q{root};
while (q.size() != 0) {
auto node = q.front();
auto left{node->left}, right{node->right};
q.pop_front();
ans.push_back(node->val);
if (right != nullptr) {
q.push_front(right);
}
if (left != nullptr) {
q.push_front(left);
}
}
return ans;
}
};
961 - 2023-11-20 14:27:13 +0300 MSK
Binary Tree Preorder Traversal
Links
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
std::vector<int> ans{};
std::deque<TreeNode*> q{root};
while (q.size() != 0) {
auto node = q.front();
q.pop_front();
if (node == nullptr) {
continue;
}
ans.push_back(node->val);
q.push_front(node->right);
q.push_front(node->left);
}
return ans;
}
};
962 - 2023-11-20 14:11:47 +0300 MSK
Minimum Amount of Time to Collect Garbage
Links
Code
class Solution {
public:
int garbageCollection(vector<string>& garbage, vector<int>& travel) {
vector<int> prefixSum(travel.size() + 1, 0);
prefixSum[1] = travel[0];
for (int i = 1; i < travel.size(); i++) {
prefixSum[i + 1] = prefixSum[i] + travel[i];
}
unordered_map<char, int> garbageLastPos;
unordered_map<char, int> garbageCount;
for (int i = 0; i < garbage.size(); i++) {
for (char c : garbage[i]) {
garbageLastPos[c] = i;
garbageCount[c]++;
}
}
char garbageTypes[3] = {'M', 'P', 'G'};
int ans = 0;
for (char c : garbageTypes) {
if (garbageCount[c]) {
ans += prefixSum[garbageLastPos[c]] + garbageCount[c];
}
}
return ans;
}
};
963 - 2023-11-19 11:31:05 +0300 MSK
Reduction Operations to Make the Array Elements Equal
Links
Code
class Solution {
public:
int reductionOperations(vector<int>& nums) {
sort(nums.begin(), nums.end());
int ans = 0;
int up = 0;
auto length {nums.size()};
for (int i = 1; i < length; ++i) {
if (nums[i] != nums[i - 1]) {
++up;
}
ans += up;
}
return ans;
}
};
964 - 2023-11-18 19:23:48 +0300 MSK
Frequency of the Most Frequent Element
Links
Code
class Solution {
public:
int maxFrequency(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int left = 0;
int ans = 0;
long curr = 0;
for (int right = 0; right < nums.size(); right++) {
long target = nums[right];
curr += target;
while ((right - left + 1) * target - curr > k) {
curr -= nums[left];
left++;
}
ans = max(ans, right - left + 1);
}
return ans;
}
};
965 - 2023-11-17 17:25:22 +0300 MSK
Odd Even Linked List
Links
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head || !head->next || !head->next->next) {
return head;
}
ListNode* odd {head};
ListNode* even {head->next};
ListNode* even_start {head->next};
while(odd->next && even->next) {
ListNode* next {even->next};
odd->next = next;
even->next = next->next;
odd = odd->next;
even = even->next;
}
odd->next = even_start;
return head;
}
};
966 - 2023-11-17 16:41:37 +0300 MSK
Dota2 Senate
Links
Code
class Solution {
public:
string predictPartyVictory(string senate) {
std::queue<int> rad, dir;
unsigned long length {senate.size()};
for (int i = 0; i < length; ++i){
if (senate[i] == 'R'){
rad.push(i);
} else {
dir.push(i);
}
}
while (!rad.empty() && !dir.empty()) {
if (rad.front() < dir.front()) {
rad.push(length);
} else {
dir.push(length);
}
++length;
rad.pop();
dir.pop();
}
return rad.empty() ? "Dire" : "Radiant";
}
};
967 - 2023-11-17 14:05:35 +0300 MSK
Decode String
Links
Code
class Solution {
public:
string decodeString(string s) {
return std::get<1>(decode(0, s));
}
std::tuple<int, string> decode(int pos, string s) {
int num {0};
string word {""};
unsigned long length {s.size()};
for(; pos < length; ++pos) {
char c = s[pos];
if(c == '[') {
auto [newPos, repeat] {decode(++pos, s)};
for(; num > 0; --num) {
word += repeat;
}
pos = newPos;
} else if (c >= '0' && c <='9') {
num = num * 10 + (c - '0');
} else if (c == ']') {
return {pos, word};
} else {
word += c;
}
}
return {pos, word};
}
};
968 - 2023-11-17 14:02:06 +0300 MSK
Decode String
Links
Code
class Solution {
public:
string decodeString(string s) {
int pos = 0;
return decode(pos, s);
}
string decode(int& pos, string s) {
int num {0};
string word {""};
unsigned long length {s.size()};
for(; pos < length; ++pos) {
char c = s[pos];
if(c == '[') {
string repeat {decode(++pos, s)};
for(; num > 0; --num) {
word += repeat;
}
} else if (c >= '0' && c <='9') {
num = num * 10 + (c - '0');
} else if (c == ']') {
return word;
} else {
word += c;
}
}
return word;
}
};
969 - 2023-11-17 13:13:32 +0300 MSK
Removing Stars From a String
Links
Code
class Solution {
public:
string removeStars(string s) {
std::string ans;
int remove {0};
for (int i = s.size() - 1; i >= 0; --i) {
char c = s[i];
if (c == '*') {
++remove;
} else if (remove == 0) {
ans += c;
} else {
--remove;
}
}
std::reverse(ans.begin(), ans.end());
return ans;
}
};
970 - 2023-11-17 13:12:34 +0300 MSK
Removing Stars From a String
Links
Code
class Solution {
public:
string removeStars(string s) {
std::string ans;
unsigned long length {s.size()};
int remove {0};
for (int i = length - 1; i >= 0; --i) {
char c = s[i];
if (c == '*') {
++remove;
continue;
}
if (remove == 0) {
ans += c;
} else {
--remove;
}
}
std::reverse(ans.begin(), ans.end());
return ans;
}
};
971 - 2023-11-17 13:02:26 +0300 MSK
Minimize Maximum Pair Sum in Array
Links
Code
class Solution {
public:
int minPairSum(vector<int>& nums) {
std::sort(nums.begin(), nums.end());
unsigned long length {nums.size()};
int maxSum {0};
for (int i = 0; i < length / 2; ++i) {
maxSum = max(maxSum, nums[i] + nums[length - i - 1]);
}
return maxSum;
}
};
972 - 2023-11-16 16:43:00 +0300 MSK
Unique Number of Occurrences
Links
Code
class Solution {
public:
bool uniqueOccurrences(vector<int>& arr) {
std::unordered_map<int, int> counts;
std::unordered_set<int> encountered;
for (int num : arr) {
counts[num] += 1;
}
for (const auto [num, count] : counts) {
if (encountered.find(count) == encountered.end()) {
encountered.insert(count);
} else {
return false;
}
}
return true;
}
};
973 - 2023-11-16 16:22:50 +0300 MSK
N-th Tribonacci Number
Links
Code
class Solution {
public:
int tribonacci(int n) {
if (n == 0) {
return 0;
}
if (n == 1 || n == 2) {
return 1;
}
int num1 {0}, num2 {1}, num3 {1};
for (int i = 3; i <= n; ++i) {
int newNum3 = num1 + num2 + num3;
num1 = num2;
num2 = num3;
num3 = newNum3;
}
return num3;
}
};
974 - 2023-11-16 14:30:47 +0300 MSK
Kth Largest Element in an Array
Links
Code
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
std::sort(nums.begin(), nums.end(), std::greater<int>());
return nums[k-1];
}
};
975 - 2023-11-16 14:18:16 +0300 MSK
Search in a Binary Search Tree
Links
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while (root != nullptr) {
if (root->val == val) {
return root;
}
if (root->val > val) {
root = root->left;
} else {
root = root->right;
}
}
return root;
}
};
976 - 2023-11-16 14:15:58 +0300 MSK
Search in a Binary Search Tree
Links
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == nullptr || root->val == val) {
return root;
}
if (val > root->val) {
return searchBST(root->right, val);
}
return searchBST(root->left, val);
}
};
977 - 2023-11-16 14:13:23 +0300 MSK
Find Pivot Index
Links
Code
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int left {0}, right {std::accumulate(nums.begin() + 1, nums.end(), 0)};
unsigned long length {nums.size()};
if (right == 0) {
return 0;
}
for (int i = 1; i < length; ++i) {
left += nums[i-1];
right -= nums[i];
if (left == right) {
return i;
}
}
return -1;
}
};
978 - 2023-11-16 14:06:30 +0300 MSK
Find the Highest Altitude
Links
Code
class Solution {
public:
int largestAltitude(vector<int>& gain) {
int att {0}, maxAtt {0};
for (int num : gain) {
att += num;
maxAtt = max(maxAtt, att);
}
return maxAtt;
}
};
979 - 2023-11-16 11:22:37 +0300 MSK
Find Unique Binary String
Links
Code
class Solution {
public:
string findDifferentBinaryString(vector<string>& nums) {
unordered_set<int> integers;
for (string num : nums) {
integers.insert(stoi(num, 0, 2));
}
int n = nums.size();
string ans;
for (int num = 0; num <= n; num++) {
if (integers.find(num) == integers.end()) {
ans = bitset<16>(num).to_string();
break;
}
}
return ans.substr(16 - n);
}
};
980 - 2023-11-15 16:53:47 +0300 MSK
Find the Difference of Two Arrays
Links
Code
class Solution {
public:
vector<int> getElementsOnlyInFirstList(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> onlyInNums1;
for (int num : nums1) {
bool existInNums2 = false;
for (int x : nums2) {
if (x == num) {
existInNums2 = true;
break;
}
}
if (!existInNums2) {
onlyInNums1.insert(num);
}
}
return vector<int> (onlyInNums1.begin(), onlyInNums1.end());
}
vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {
return {getElementsOnlyInFirstList(nums1, nums2), getElementsOnlyInFirstList(nums2, nums1)};
}
};
981 - 2023-11-15 16:12:27 +0300 MSK
Increasing Triplet Subsequence
Links
Code
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
auto length{nums.size()};
int num1{INT_MAX}, num2{INT_MAX};
for (int num : nums) {
if (num <= num1) {
num1 = num;
} else if (num <= num2) {
num2 = num;
} else {
return true;
}
}
return false;
}
};
982 - 2023-11-15 15:18:40 +0300 MSK
Maximum Element After Decreasing and Rearranging
Links
Code
class Solution {
public:
int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {
std::sort(arr.begin(), arr.end());
auto length{arr.size()};
int prev{1};
for (int i = 1; i < length; ++i) {
if (arr[i] != prev) {
++prev;
}
}
return prev;
}
};
983 - 2023-11-15 15:17:30 +0300 MSK
Maximum Element After Decreasing and Rearranging
Links
Code
class Solution {
public:
int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {
std::sort(arr.begin(), arr.end());
auto length{arr.size()};
int prev{1};
for (int i = 1; i < length; ++i) {
if (arr[i] == prev) {
continue;
}
++prev;
}
return prev;
}
};
984 - 2023-11-14 15:39:29 +0300 MSK
Unique Length-3 Palindromic Subsequences
Links
Code
class Solution {
public:
int countPalindromicSubsequence(string s) {
unordered_set<char> letters;
for (char c : s) {
letters.insert(c);
}
int ans = 0;
for (char letter : letters) {
int i = -1;
int j = 0;
for (int k = 0; k < s.size(); k++) {
if (s[k] == letter) {
if (i == -1) {
i = k;
}
j = k;
}
}
unordered_set<char> between;
for (int k = i + 1; k < j; k++) {
between.insert(s[k]);
}
ans += between.size();
}
return ans;
}
};
985 - 2023-11-13 20:24:55 +0300 MSK
Reverse Vowels of a String
Links
Code
class Solution {
public:
bool isVowel(char ch) {
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
}
string reverseVowels(string s) {
unsigned long length{s.size()};
unsigned long left{0}, right{length-1};
while (left < right) {
char chLeft{s[left]};
char chRight{s[right]};
if (!isVowel(chLeft)) {
++left;
} else if (!isVowel(chRight)) {
--right;
} else {
s[left] = chRight;
s[right] = chLeft;
++left;
--right;
}
}
return s;
}
};
986 - 2023-11-13 10:42:13 +0300 MSK
Sort Vowels in a String
Links
Code
class Solution {
public:
// Returns true if the character is a vowel.
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'o'|| c == 'u'|| c == 'i'
|| c == 'A' || c == 'E' || c == 'O'|| c == 'U'|| c == 'I';
}
string sortVowels(string s) {
unordered_map<char, int> count;
// Store the frequencies for each character.
for (char c : s) {
if (isVowel(c)) {
count[c]++;
}
}
// Sorted string having all the vowels.
string sortedVowel = "AEIOUaeiou";
string ans;
int j = 0;
for (int i = 0; i < s.size(); i++) {
if (!isVowel(s[i])) {
ans += s[i];
} else {
// Skip to the character which is having remaining count.
while (count[sortedVowel[j]] == 0) {
j++;
}
ans += sortedVowel[j];
count[sortedVowel[j]]--;
}
}
return ans;
}
};
987 - 2023-11-13 10:40:23 +0300 MSK
Sort Vowels in a String
Links
Code
class Solution {
public:
string sortVowels(string s) {
std::map<char, int> vowels{
{'A', 0}, {'E', 0}, {'I', 0}, {'O', 0}, {'U', 0},
{'a', 0}, {'e', 0}, {'i', 0}, {'o', 0}, {'u', 0}
};
unsigned long length{ s.size() };
for (char ch : s) {
if (vowels.contains(ch)) {
++vowels[ch];
}
}
for (int i = 0; i < length; ++i) {
const char ch = s[i];
if (!vowels.contains(ch)) {
continue;
}
for (const auto& [orderChar, count] : vowels) {
if (count > 0) {
s[i] = orderChar;
--vowels[orderChar];
break;
}
}
}
return s;
}
};
988 - 2023-11-13 10:38:46 +0300 MSK
Sort Vowels in a String
Links
Code
class Solution {
public:
string sortVowels(string s) {
std::map<char, int> vowels{
{'A', 0}, {'E', 0}, {'I', 0}, {'O', 0}, {'U', 0},
{'a', 0}, {'e', 0}, {'i', 0}, {'o', 0}, {'u', 0}
};
const char order[10]{ 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u' };
unsigned long length{ s.size() };
for (char ch : s) {
if (vowels.contains(ch)) {
++vowels[ch];
}
}
for (int i = 0; i < length; ++i) {
const char ch = s[i];
if (!vowels.contains(ch)) {
continue;
}
for (char orderChar : order) {
if (vowels[orderChar] > 0) {
s[i] = orderChar;
--vowels[orderChar];
break;
}
}
}
return s;
}
};
989 - 2023-11-12 17:00:22 +0300 MSK
Maximum Average Subarray I
Links
Code
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int length = nums.size();
double sum = std::accumulate(nums.begin(), nums.begin() + k , 0);
double maxSum = sum;
for (int i = k; i < length; ++i) {
sum += nums[i] - nums[i-k];
maxSum = max(sum, maxSum);
}
return maxSum / k;
}
};
990 - 2023-11-12 16:08:04 +0300 MSK
String Compression
Links
Code
class Solution {
public:
int compress(vector<char>& chars) {
int i = 0, res = 0;
int length = chars.size();
while (i < length) {
int groupLength = 1;
while (i + groupLength < length && chars[i + groupLength] == chars[i]) {
groupLength++;
}
chars[res++] = chars[i];
if (groupLength > 1) {
for (char c : to_string(groupLength)) {
chars[res++] = c;
}
}
i += groupLength;
}
return res;
}
};
991 - 2023-11-12 15:43:55 +0300 MSK
Can Place Flowers
Links
Code
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int curZeros = flowerbed[0] == 0 ? 2 : 0;
int length = flowerbed.size();
int ans = 0;
for (int i = 1; i < length; ++i) {
if (flowerbed[i] == 0) {
curZeros += 1;
continue;
}
ans += (curZeros - 1) / 2;
curZeros = 0;
if (ans >= n) {
return true;
}
}
ans += curZeros / 2;
return ans >= n;
}
};
992 - 2023-11-12 15:41:26 +0300 MSK
Can Place Flowers
Links
Code
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int curZeros = 0, length = flowerbed.size();
if (flowerbed[0] == 0) {
curZeros = 2;
}
int ans = 0;
for (int i = 1; i < length; ++i) {
bool isFlower = flowerbed[i] == 1;
if (!isFlower) {
curZeros += 1;
continue;
}
ans += (curZeros - 1) / 2;
curZeros = 0;
if (ans >= n) {
return true;
}
}
ans += curZeros / 2;
return ans >= n;
}
};
993 - 2023-11-12 11:40:25 +0300 MSK
Bus Routes
Links
Code
class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {
if (source == target) {
return 0;
}
unordered_map<int, vector<int>> adjList;
// Create a map from the bus stop to all the routes that include this stop.
for (int route = 0; route < routes.size(); route++) {
for (auto stop : routes[route]) {
// Add all the routes that have this stop.
adjList[stop].push_back(route);
}
}
queue<int> q;
unordered_set<int> vis;
// Insert all the routes in the queue that have the source stop.
for (auto route : adjList[source]){
q.push(route);
vis.insert(route);
}
int busCount = 1;
while (q.size()) {
int size = q.size();
for (int i = 0; i < size; i++) {
int route = q.front(); q.pop();
// Iterate over the stops in the current route.
for (auto stop: routes[route]) {
// Return the current count if the target is found.
if (stop == target) {
return busCount;
}
// Iterate over the next possible routes from the current stop.
for (auto nextRoute : adjList[stop]) {
if (!vis.count(nextRoute)) {
vis.insert(nextRoute);
q.push(nextRoute);
}
}
}
}
busCount++;
}
return -1;
}
};
994 - 2023-11-11 16:10:00 +0300 MSK
Fibonacci Number
Links
Code
class Solution {
public:
int fib(int n) {
if (n < 2) {
return n;
}
int cur = 1, prev = 0;
for (int i = 2; i <= n; ++i) {
int newVal = cur + prev;
prev = cur;
cur = newVal;
}
return cur;
}
};
995 - 2023-11-11 16:06:23 +0300 MSK
Remove Linked List Elements
Links
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
head = new ListNode(-1, head);
auto ans = head;
while (head) {
auto next = head->next;
if (next && next->val == val) {
head->next = next->next;
} else {
head = next;
}
}
return ans->next;
}
};
996 - 2023-11-11 16:06:11 +0300 MSK
Remove Linked List Elements
Links
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
head = new ListNode(-1, head);
auto ans = head;
while (head) {
auto next = head->next;
if (next && next->val == val) {
head->next = next->next;
} else {
head = head->next;
}
}
return ans->next;
}
};
997 - 2023-11-11 15:52:58 +0300 MSK
Valid Parentheses
Links
Code
class Solution {
public:
bool isValid(string s) {
std::vector<char> stack;
for (const auto& ch : s) {
switch (ch){
case '[':
case '{':
case '(':
stack.push_back(ch);
break;
case ')':
if (stack.empty() || stack.back() != '(') {
return false;
}
stack.pop_back();
break;
case '}':
if (stack.empty() || stack.back() != '{') {
return false;
}
stack.pop_back();
break;
case ']':
if (stack.empty() || stack.back() != '[') {
return false;
}
stack.pop_back();
break;
}
}
return stack.size() == 0;
}
};
998 - 2023-11-11 15:43:36 +0300 MSK
Two Sum
Links
Code
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::map<int, int> numToIndex;
int length = nums.size();
std::vector<int> ans;
for (int i = 0; i < length; ++i) {
int num = nums[i];
int diff = target - num;
if (numToIndex.contains(diff)) {
ans = {numToIndex[diff], i};
break;
}
numToIndex[num] = i;
}
return ans;
}
};
999 - 2023-11-11 15:32:34 +0300 MSK
Reverse Words in a String
Links
Code
class Solution {
public:
string reverseWords(string s) {
string ans = "";
string temp = "";
int length = s.length();
int j = 0;
for (j = 0; s[j] == ' ' && j < length; ++j) { }
for (int i = length - 1; i >= j; --i) {
if(s[i] == ' '){
if(temp != ""){
ans = ans + temp + ' ';
temp = "";
}
continue;
}
else{
temp = s[i] + temp;
}
}
return ans + temp;
}
};
1000 - 2023-11-11 15:18:39 +0300 MSK
Reverse Linked List
Links
Code
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;
while(curr != NULL){
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
1001 - 2023-11-11 15:08:55 +0300 MSK
Move Zeroes
Links
Code
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int length = nums.size();
int lastNonZeroFoundAt = 0;
for (int i = 0; i < length; ++i) {
if (nums[i] != 0) {
swap(nums[lastNonZeroFoundAt], nums[i]);
lastNonZeroFoundAt += 1;
}
}
}
};
1002 - 2023-11-11 15:06:06 +0300 MSK
Move Zeroes
Links
Code
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int lastNonZeroFoundAt = 0;
int length = nums.size();
for (int i = 0; i < length; ++i) {
int num = nums[i];
if (num == 0) {
continue;
}
if (i != lastNonZeroFoundAt) {
nums[lastNonZeroFoundAt] = num;
}
lastNonZeroFoundAt += 1;
}
for (int i = lastNonZeroFoundAt; i < length; i++) {
nums[i] = 0;
}
}
};
1003 - 2023-11-11 14:51:09 +0300 MSK
Design Graph With Shortest Path Calculator
Links
Code
class Graph {
public:
vector<vector<pair<int, int>>> adjList;
Graph(int n, vector<vector<int>>& edges) {
adjList.resize(n);
for (auto& e: edges)
adjList[e[0]].push_back(make_pair(e[1], e[2]));
}
void addEdge(vector<int> edge) {
adjList[edge[0]].push_back(make_pair(edge[1], edge[2]));
}
int shortestPath(int node1, int node2) {
int n = adjList.size();
priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;
vector<int> costForNode(n, INT_MAX);
costForNode[node1] = 0;
pq.push({0, node1});
while (!pq.empty()) {
int currCost = pq.top()[0];
int currNode = pq.top()[1];
pq.pop();
if (currCost > costForNode[currNode]) {
continue;
}
if (currNode == node2) {
return currCost;
}
for (auto& neighbor : adjList[currNode]) {
int neighborNode = neighbor.first;
int cost = neighbor.second;
int newCost = currCost + cost;
if (newCost < costForNode[neighborNode]) {
costForNode[neighborNode] = newCost;
pq.push({newCost, neighborNode});
}
}
}
return -1;
}
};
1004 - 2023-11-10 19:50:03 +0300 MSK
Merge Strings Alternately
Links
Code
class Solution {
public:
string mergeAlternately(string word1, string word2) {
int m = word1.size();
int n = word2.size();
string result = "";
for (int i = 0; i < max(m, n); i++) {
if (i < m) {
result.push_back(word1[i]);
}
if (i < n) {
result.push_back(word2[i]);
}
}
return result;
}
};
1005 - 2023-11-10 19:49:28 +0300 MSK
Merge Strings Alternately
Links
Code
class Solution {
public:
string mergeAlternately(string word1, string word2) {
int l1 = word1.size(), l2 = word2.size();
string result = "";
int i = 0, j = 0;
while (i < l1 || j < l2) {
if (i < l1) {
result.push_back(word1[i++]);
}
if (j < l2) {
result.push_back(word2[j++]);
}
}
return result;
}
};
1006 - 2023-11-10 19:47:59 +0300 MSK
Merge Strings Alternately
Links
Code
class Solution {
public:
string mergeAlternately(string word1, string word2) {
std::stringstream ans;
int l1 = word1.size(), l2 = word2.size();
int lMax = max(l1, l2);
for (int i = 0; i < lMax; ++i) {
if (i < l1) {
ans << word1[i];
} else {
ans << word2.substr(i);
break;
}
if (i < l2) {
ans << word2[i];
} else {
ans << word1.substr(i + 1);
break;
}
}
return ans.str();
}
};
1007 - 2023-11-10 19:34:50 +0300 MSK
Subrectangle Queries
Links
Code
class SubrectangleQueries {
vector<vector<int>> res;
public:
SubrectangleQueries(vector<vector<int>>& rectangle) {
res=rectangle;
}
void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
for(int i = row1; i <= row2; ++i) {
for(int j= col1; j <= col2; ++j) {
res[i][j] = newValue;
}
}
}
int getValue(int row, int col) {
return res[row][col];
}
};
/**
* Your SubrectangleQueries object will be instantiated and called as such:
* SubrectangleQueries* obj = new SubrectangleQueries(rectangle);
* obj->updateSubrectangle(row1,col1,row2,col2,newValue);
* int param_2 = obj->getValue(row,col);
*/
1008 - 2023-11-10 19:18:28 +0300 MSK
Subrectangle Queries
Links
Code
class SubrectangleQueries {
public:
std::vector<std::vector<int>> rectangle;
std::vector<std::array<int, 5>> updates;
SubrectangleQueries(vector<vector<int>>& rectangle) {
this->rectangle = rectangle;
}
void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
this->updates.push_back({row1, col1, row2, col2, newValue});
}
int getValue(int row, int col) {
int length = this->updates.size();
for (int i = length - 1; i >= 0; --i) {
auto const [row1, col1, row2, col2, newValue] = this->updates[i];
if (row < row1 || row > row2 || col < col1 || col > col2) {
continue;
}
return newValue;
}
return this->rectangle[row][col];
}
};
/**
* Your SubrectangleQueries object will be instantiated and called as such:
* SubrectangleQueries* obj = new SubrectangleQueries(rectangle);
* obj->updateSubrectangle(row1,col1,row2,col2,newValue);
* int param_2 = obj->getValue(row,col);
*/
1009 - 2023-11-10 18:37:59 +0300 MSK
Operations on Tree
Links
Code
class LockingTree {
public:
std::vector<int> parents, locked;
std::vector<std::vector<int>> children;
LockingTree(vector<int>& parent) {
int length = parent.size();
this->children.resize(length);
this->locked.resize(length, -1);
this->parents = parent;
for (int i = 1; i < length; ++i) {
this->children[this->parents[i]].push_back(i);
}
}
bool lock(int num, int user) {
if (this->locked[num] != -1) {
return false;
}
this->locked[num] = user;
return true;
}
bool unlock(int num, int user) {
if (this->locked[num] != user) {
return false;
}
this->locked[num] = -1;
return true;
}
bool upgrade(int num, int user) {
if (this->locked[num] != -1) {
return false;
}
int parent = this->parents[num];
while (parent != -1) {
if (this->locked[parent] != -1) {
return false;
}
parent = this->parents[parent];
}
if (!this->unlockDesc(num)) {
return false;
}
this->locked[num] = user;
return true;
}
bool unlockDesc(int parent) {
bool hasLocked = false;
for (auto const& child : this->children[parent]) {
if (this->locked[child] != -1) {
this->locked[child] = -1;
hasLocked = true;
}
bool descHasLocked = unlockDesc(child);
if (descHasLocked) {
hasLocked = true;
}
}
return hasLocked;
}
};
/**
* Your LockingTree object will be instantiated and called as such:
* LockingTree* obj = new LockingTree(parent);
* bool param_1 = obj->lock(num,user);
* bool param_2 = obj->unlock(num,user);
* bool param_3 = obj->upgrade(num,user);
*/
1010 - 2023-11-10 16:30:33 +0300 MSK
Implement Stack using Queues
Links
Code
class MyStack {
public:
std::vector<int> v;
MyStack() {
this->v = {};
}
void push(int x) {
this->v.push_back(x);
}
int pop() {
int last = this->v.back();
this->v.pop_back();
return last;
}
int top() {
return this->v.back();
}
bool empty() {
return this->v.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
1011 - 2023-11-10 13:30:38 +0300 MSK
Restore the Array From Adjacent Pairs
Links
Code
func restoreArray(adjacentPairs [][]int) []int {
// [[2,1],[3,4],[3,2]]
// 1: [2]
// 2: [1, 3]
// 3: [2, 4]
// 4: [3]
// Output: [1,2,3,4]
graph := map[int][]int{}
length := len(adjacentPairs) + 1
ans := make([]int, length)
for _, pair := range adjacentPairs {
num1, num2 := pair[0], pair[1]
graph[num1] = append(graph[num1], num2)
graph[num2] = append(graph[num2], num1)
}
for node, edges := range graph {
if len(edges) == 1 {
ans[0], ans[1] = node, edges[0]
break
}
}
cur, prev := ans[1], ans[0]
for i := 2; i < length; i++ {
for _, target := range graph[cur] {
if target != prev {
ans[i] = target
cur, prev = target, cur
break
}
}
}
return ans
}
1012 - 2023-11-10 13:24:56 +0300 MSK
Restore the Array From Adjacent Pairs
Links
Code
func restoreArray(adjacentPairs [][]int) []int {
// [[2,1],[3,4],[3,2]]
// 1: [2]
// 2: [1, 3]
// 3: [2, 4]
// 4: [3]
// Output: [1,2,3,4]
graph := map[int][]int{}
for _, pair := range adjacentPairs {
num1, num2 := pair[0], pair[1]
graph[num1] = append(graph[num1], num2)
graph[num2] = append(graph[num2], num1)
}
length := len(adjacentPairs) + 1
ans := make([]int, length)
for node, edges := range graph {
if len(edges) == 1 {
ans[0], ans[1] = node, edges[0]
break
}
}
for i := 2; i < length; i++ {
cur, prev := ans[i-1], ans[i-2]
for _, target := range graph[cur] {
if target != prev {
ans[i] = target
}
}
}
return ans
}
1013 - 2023-11-09 10:03:41 +0300 MSK
Count Number of Homogenous Substrings
Links
Code
func countHomogenous(s string) int {
var (
mod int64 = 1000000007
total int64 = 0
count int64 = 0
cur = s[0]
)
for i := 0; i < len(s); i++ {
char := s[i]
if char == cur {
count++
} else {
count = 1
cur = char
}
total += count
}
return int(total % mod)
}
1014 - 2023-11-08 11:09:02 +0300 MSK
Determine if a Cell Is Reachable at a Given Time
Links
Code
func isReachableAtTime(sx int, sy int, fx int, fy int, t int) bool {
vert := abs(sy, fy)
dist := vert + max(0, abs(sx, fx) - vert)
if dist == 0 && t == 1 {
return false
}
return dist <= t
}
func abs(x, y int) int {
if x > y {
return x - y
}
return y - x
}
1015 - 2023-11-07 21:56:45 +0300 MSK
Design HashSet
Links
Code
type MyHashSet struct {
m map[int]struct{}
}
func Constructor() MyHashSet {
return MyHashSet{map[int]struct{}{}}
}
func (this *MyHashSet) Add(key int) {
this.m[key] = struct{}{}
}
func (this *MyHashSet) Remove(key int) {
delete(this.m, key)
}
func (this *MyHashSet) Contains(key int) bool {
_, ok := this.m[key]
return ok
}
/**
* Your MyHashSet object will be instantiated and called as such:
* obj := Constructor();
* obj.Add(key);
* obj.Remove(key);
* param_3 := obj.Contains(key);
*/
1016 - 2023-11-07 21:50:49 +0300 MSK
Merge Strings Alternately
Links
Code
func mergeAlternately(word1 string, word2 string) string {
var sb strings.Builder
length1, length2 := len(word1), len(word2)
for i := 0; i < max(length1, length2); i++ {
if i == length1 {
sb.WriteString(word2[i:length2])
break
}
if i == length2 {
sb.WriteString(word1[i:length1])
break
}
sb.WriteByte(word1[i])
sb.WriteByte(word2[i])
}
return sb.String()
}
1017 - 2023-11-07 19:07:48 +0300 MSK
Eliminate Maximum Number of Monsters
Links
Code
func eliminateMaximum(dist []int, speed []int) int {
arrival := []float32{}
length := len(dist)
for i := 0; i < length; i++ {
arrival = append(arrival, float32(dist[i]) / float32(speed[i]))
}
slices.Sort(arrival)
ans := 0
for i := 0; i < length; i++ {
if arrival[i] <= float32(i) {
break
}
ans += 1
}
return ans
}
1018 - 2023-11-06 18:41:34 +0300 MSK
Design Circular Deque
Links
Code
type MyCircularDeque struct {
list []int
size int
}
func Constructor(k int) MyCircularDeque {
return MyCircularDeque{[]int{}, k}
}
func (this *MyCircularDeque) InsertFront(value int) bool {
if this.IsFull() {
return false
}
this.list = append([]int{value}, this.list...)
return true
}
func (this *MyCircularDeque) InsertLast(value int) bool {
if this.IsFull() {
return false
}
this.list = append(this.list, value)
return true
}
func (this *MyCircularDeque) DeleteFront() bool {
if this.IsEmpty() {
return false
}
this.list = this.list[1:]
return true
}
func (this *MyCircularDeque) DeleteLast() bool {
if this.IsEmpty() {
return false
}
this.list = this.list[:len(this.list) - 1]
return true
}
func (this *MyCircularDeque) GetFront() int {
if this.IsEmpty() {
return -1
}
return this.list[0]
}
func (this *MyCircularDeque) GetRear() int {
if this.IsEmpty() {
return -1
}
return this.list[len(this.list) - 1]
}
func (this *MyCircularDeque) IsEmpty() bool {
return len(this.list) == 0
}
func (this *MyCircularDeque) IsFull() bool {
return len(this.list) == this.size
}
/**
* Your MyCircularDeque object will be instantiated and called as such:
* obj := Constructor(k);
* param_1 := obj.InsertFront(value);
* param_2 := obj.InsertLast(value);
* param_3 := obj.DeleteFront();
* param_4 := obj.DeleteLast();
* param_5 := obj.GetFront();
* param_6 := obj.GetRear();
* param_7 := obj.IsEmpty();
* param_8 := obj.IsFull();
*/
1019 - 2023-11-06 14:57:33 +0300 MSK
Seat Reservation Manager
Links
Code
type SeatManager struct {
heap *binaryheap.Heap
}
func Constructor(n int) SeatManager {
heap := binaryheap.NewWithIntComparator()
for i := 1; i <= n; i++ {
heap.Push(i)
}
return SeatManager{heap}
}
func (this *SeatManager) Reserve() int {
val, _ := this.heap.Pop()
return val.(int)
}
func (this *SeatManager) Unreserve(seatNumber int) {
this.heap.Push(seatNumber)
}
/**
* Your SeatManager object will be instantiated and called as such:
* obj := Constructor(n);
* param_1 := obj.Reserve();
* obj.Unreserve(seatNumber);
*/
1020 - 2023-11-06 14:49:27 +0300 MSK
Seat Reservation Manager
Links
Code
type SeatManager struct {
seats []bool
}
func Constructor(n int) SeatManager {
return SeatManager{make([]bool, n)}
}
func (this *SeatManager) Reserve() int {
for i, num := range this.seats {
if !num {
this.seats[i] = true
return i + 1
}
}
return -1
}
func (this *SeatManager) Unreserve(seatNumber int) {
this.seats[seatNumber-1] = false
}
/**
* Your SeatManager object will be instantiated and called as such:
* obj := Constructor(n);
* param_1 := obj.Reserve();
* obj.Unreserve(seatNumber);
*/
1021 - 2023-11-05 21:02:40 +0300 MSK
Serialize and Deserialize Binary Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type Codec struct {
}
func Constructor() Codec {
return Codec{}
}
// Serializes a tree to a single string.
func (this *Codec) serialize(root *TreeNode) string {
if root == nil {
return ""
}
var buffer bytes.Buffer
queue := []*TreeNode{root}
for length := len(queue); length > 0; length = len(queue) {
for i := 0; i < length; i++ {
node := queue[i]
if node != nil {
buffer.WriteString(strconv.Itoa(node.Val))
queue = append(queue, node.Left, node.Right)
}
buffer.WriteString(",")
}
queue = queue[length:]
}
ans := buffer.String()
return ans[:len(ans)-1]
}
// Deserializes your encoded data to tree.
func (this *Codec) deserialize(data string) *TreeNode {
nodes := []*TreeNode{}
for _, str := range strings.Split(data, ",") {
if str == "" {
nodes = append(nodes, nil)
} else {
num, _ := strconv.Atoi(str)
nodes = append(nodes, &TreeNode{num, nil, nil})
}
}
start := 0
length := len(nodes)
for _, node := range nodes {
if node == nil {
continue
}
left, right := 2 * start + 1, 2 * start + 2
if left < length {
node.Left = nodes[left]
}
if right < length {
node.Right = nodes[right]
}
start++
}
return nodes[0]
}
/**
* Your Codec object will be instantiated and called as such:
* ser := Constructor();
* deser := Constructor();
* data := ser.serialize(root);
* ans := deser.deserialize(data);
*/
1022 - 2023-11-05 12:06:04 +0300 MSK
Find the Winner of an Array Game
Links
Code
func getWinner(arr []int, k int) int {
if k == 1 {
return max(arr[0], arr[1])
}
length := len(arr)
if k >= length {
return slices.Max(arr)
}
curWinner, winCount := arr[0], 0
for _, num := range arr[1:] {
if curWinner > num {
winCount++
} else {
curWinner = num
winCount = 1
}
if winCount == k {
return curWinner
}
}
return curWinner
}
1023 - 2023-11-05 12:01:59 +0300 MSK
Find the Winner of an Array Game
Links
Code
func getWinner(arr []int, k int) int {
curMax, winCount := arr[0], 0
i, length := 1, len(arr)
for {
num := arr[i]
if num > curMax {
curMax = num
winCount = 1
} else {
winCount++
}
if winCount == k {
return curMax
}
i = (i + 1) % length
}
return -1
}
1024 - 2023-11-04 13:31:04 +0300 MSK
Find Median from Data Stream
Links
Code
type MaxHeap []int
func (m MaxHeap) Len() int { return len(m) }
func (m MaxHeap) Less(i, j int) bool { return m[i] > m[j] }
func (m MaxHeap) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m *MaxHeap) Pop() interface{} {
v := (*m)[len(*m)-1]
*m = (*m)[:len(*m)-1]
return v
}
func (m *MaxHeap) Push(v interface{}) { *m = append(*m, v.(int)) }
func (m MaxHeap) Top() int { return m[0] }
type MinHeap []int
func (m MinHeap) Len() int { return len(m) }
func (m MinHeap) Less(i, j int) bool { return m[i] < m[j] }
func (m MinHeap) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m *MinHeap) Pop() interface{} {
v := (*m)[len(*m)-1]
*m = (*m)[:len(*m)-1]
return v
}
func (m *MinHeap) Push(v interface{}) { *m = append(*m, v.(int)) }
func (m MinHeap) Top() int { return m[0] }
type MedianFinder struct {
left MaxHeap
right MinHeap
}
func Constructor() MedianFinder {
return MedianFinder{}
}
func (mf *MedianFinder) AddNum(num int) {
if len(mf.left) + len(mf.right) == 0 {
heap.Push(&(mf.left), num)
return
}
for {
if len(mf.left) < len(mf.right) {
if num <= mf.right.Top() {
heap.Push(&(mf.left), num)
return
} else {
v := heap.Pop(&(mf.right))
heap.Push(&(mf.left), v)
}
} else {
if num >= mf.left.Top() {
heap.Push(&(mf.right), num)
return
} else {
v := heap.Pop(&(mf.left))
heap.Push(&(mf.right), v)
}
}
}
}
func (mf *MedianFinder) FindMedian() float64 {
if len(mf.left) == len(mf.right) {
return float64(mf.left.Top() + mf.right.Top()) / 2.0
} else if len(mf.left) > len(mf.right) {
return float64(mf.left.Top())
} else {
return float64(mf.right.Top())
}
}
1025 - 2023-11-04 13:30:46 +0300 MSK
IPO
Links
Code
type Project struct {
profit, capital int
}
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func findMaximizedCapital(k int, w int, profits []int, capital []int) int {
n := len(profits)
projects := make([]Project, n)
for i := range profits {
projects[i] = Project{profits[i], capital[i]}
}
sort.Slice(projects, func (i, j int) bool {
return projects[i].capital < projects[j].capital
})
q := &IntHeap{}
heap.Init(q)
ptr := 0
for i := 0; i < k; i++ {
for ptr < n && projects[ptr].capital <= w {
heap.Push(q, projects[ptr].profit)
ptr++
}
if q.Len() == 0 {
break
}
w += heap.Pop(q).(int)
}
return w
}
1026 - 2023-11-04 13:30:28 +0300 MSK
Find Peak Element
Links
Code
func findPeakElement(nums []int) int {
left := 0
right := len(nums) - 1
for left < right {
mid := left + (right - left) / 2
if nums[mid] > nums[mid+1] {
// The peak is in the left half
right = mid
} else {
// The peak is in the right half
left = mid + 1
}
}
return left
}
1027 - 2023-11-04 13:30:08 +0300 MSK
Merge k Sorted Lists
Links
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeKLists(lists []*ListNode) *ListNode {
n:=len(lists)
if n==0{
return nil
}
curr:=lists[0]
if n==1{
return curr
}
for i:=1;i<n;i++{
curr=mergeList(curr,lists[i])
}
return curr
}
func mergeList(l1,l2 *ListNode) *ListNode {
head:=&ListNode{}
curr:=head
for l1!=nil && l2!=nil{
if l1.Val<l2.Val{
curr.Next=l1
l1=l1.Next
curr=curr.Next
}else{
curr.Next=l2
l2=l2.Next
curr=curr.Next
}
}
if l1 != nil {
curr.Next = l1
} else if l2 != nil {
curr.Next = l2
}
return head.Next
}
1028 - 2023-11-04 13:29:52 +0300 MSK
Construct Quad Tree
Links
Code
/**
* Definition for a QuadTree node.
* type Node struct {
* Val bool
* IsLeaf bool
* TopLeft *Node
* TopRight *Node
* BottomLeft *Node
* BottomRight *Node
* }
*/
func construct(grid [][]int) *Node {
var dfs func(y0, x0, width int) *Node
dfs = func(y0, x0, width int) *Node {
if width == 1 {
return &Node{
Val: grid[y0][x0] == 1,
IsLeaf: true,
}
}
w := width / 2
topLeft := dfs(y0, x0, w)
topRight := dfs(y0, x0+w, w)
bottomLeft := dfs(y0+w, x0, w)
bottomRight := dfs(y0+w, x0+w, w)
var node *Node
if topLeft.Val == topRight.Val && bottomLeft.Val == bottomRight.Val && topLeft.Val == bottomLeft.Val &&
topLeft.IsLeaf && topRight.IsLeaf && bottomLeft.IsLeaf && bottomRight.IsLeaf {
node = &Node{
Val: topLeft.Val,
IsLeaf: true,
}
} else {
node = &Node{
Val: true,
IsLeaf: false,
TopLeft: topLeft,
TopRight: topRight,
BottomLeft: bottomLeft,
BottomRight: bottomRight,
}
}
return node
}
return dfs(0, 0, len(grid))
}
1029 - 2023-11-04 13:29:35 +0300 MSK
N-Queens II
Links
Code
func totalNQueens(n int) int {
sCol:=make([]bool,n)
sD1:=make([]bool,2*n)
sD2:=make([]bool,2*n)
return helper(0,n,sCol,sD1,sD2)
}
func helper(r,n int,sCol,sD1,sD2 []bool) int{
if r==n{
return 1
}
res:=0
for i:=0; i < n; i++ {
if !sCol[i] && !sD1[i+r] && !sD2[(r-i)+n]{
// board[r][i]=true
sCol[i]=true
sD1[i+r]=true
sD2[(r-i)+n]=true
res=res+helper(r+1,n,sCol,sD1,sD2)
// board[r][i]=false
sCol[i]=false
sD1[i+r]=false
sD2[(r-i)+n]=false
}
}
return res
}
1030 - 2023-11-04 13:29:17 +0300 MSK
Word Search II
Links
Code
type Node struct {
children [26]*Node
word string
}
func (n *Node) Insert(word string) {
cur := n
for _, c := range word {
idx := c - 'a'
if cur.children[idx] == nil {
cur.children[idx] = &Node{}
}
cur = cur.children[idx]
}
cur.word = word
}
func (n *Node) IsEmpty() bool {
for _, child := range n.children {
if child != nil {
return false
}
}
return true
}
func (n *Node) Remove(word string) bool {
if len(word) == 0 {
n.word = ""
return n.IsEmpty()
}
child := n.children[word[0]-'a']
if child.Remove(word[1:]) {
n.children[word[0]-'a'] = nil
return n.IsEmpty()
}
return false
}
func dfs(board [][]byte, r, c int, root, cur *Node, res *[]string) {
rc := board[r][c]
board[r][c] = 0
if cur.word != "" {
*res = append(*res, cur.word)
root.Remove(cur.word)
}
ds := [5]int{0, 1, 0, -1, 0}
for i := 0; i < len(ds)-1; i++ {
dr, dc := r+ds[i], c+ds[i+1]
if dr < 0 || dr >= len(board) || dc < 0 || dc >= len(board[0]) {
continue
}
b := board[dr][dc]
if b == 0 || cur.children[b-'a'] == nil {
continue
}
dfs(board, dr, dc, root, cur.children[b-'a'], res)
}
board[r][c] = rc
}
func findWords(board [][]byte, words []string) []string {
m, n := len(board), len(board[0])
res, trie, has := []string{}, &Node{}, map[string]bool{}
for r := 0; r < m; r++ {
for c := 0; c < n-1; c++ {
p := string(board[r][c]) + string(board[r][c+1])
has[p] = true
}
}
for r := 0; r < m-1; r++ {
for c := 0; c < n; c++ {
p := string(board[r][c]) + string(board[r+1][c])
has[p] = true
}
}
for _, word := range words {
valid := true
for i := 0; i < len(word)-1; i++ {
a, b := string(word[i]), string(word[i+1])
if !has[a+b] && !has[b+a] {
valid = false
break
}
}
if valid {
trie.Insert(word)
}
}
for r := 0; r < m; r++ {
for c := 0; c < n; c++ {
b := board[r][c]
if trie.children[b-'a'] != nil {
dfs(board, r, c, trie, trie.children[b-'a'], &res)
}
}
}
return res
}
1031 - 2023-11-04 13:28:50 +0300 MSK
Word Ladder
Links
Code
func ladderLength(beginWord string, endWord string, wordList []string) int {
set := make(map[string]struct{}, len(wordList))
present := false
for _, v := range wordList {
if endWord == v {
present = true
}
set[v] = struct{}{}
}
if !present {
return 0
}
set[beginWord] = struct{}{}
q := []string{beginWord}
depth := 1
breadth := 0
breadth = len(q)
for ;breadth > 0; {
s := q[0]
if s == endWord {
return depth
}
for i:='a'; i <= 'z'; i += 1 {
for j := 0; j<len(s); j++ {
if rune(s[j]) != i {
temp := s[:j] + string(i) + s[j+1:]
if _, ok := set[temp]; !ok {
continue
}
q = append(q, temp)
delete(set, s)
}
}
}
q = q[1:]
breadth -= 1
if breadth == 0 {
breadth = len(q)
depth += 1
}
}
return 0
}
1032 - 2023-11-04 13:28:04 +0300 MSK
Course Schedule II
Links
Code
func findOrder(numCourses int, prerequisites [][]int) []int {
//build the graph
graph := make([][]int,numCourses)
in_degree := make([]int,numCourses)
for _,v := range prerequisites{
graph[v[1]] = append(graph[v[1]], v[0])
in_degree[v[0]]++
}
frontier := []int{}
for i,v := range in_degree{
if v==0{
frontier = append(frontier,i)
}
}
result := []int{}
for len(frontier)!=0{
cur := frontier[0]
frontier = frontier[1:]
result = append(result,cur)
for _,v := range graph[cur]{
in_degree[v]--
if in_degree[v]==0{
frontier = append(frontier,v)
}
}
}
if len(result)==numCourses{
return result
}
return []int{}
}
1033 - 2023-11-04 13:27:48 +0300 MSK
Binary Tree Maximum Path Sum
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxPathSum(root *TreeNode) int {
ans := -1 << 63
maxPath(root, &ans)
return ans
}
func maxPath(root *TreeNode, ans *int) int {
if root == nil {
return 0
}
leftPathSum := maxPath(root.Left, ans)
rightPathSum := maxPath(root.Right, ans)
*ans = max(*ans, leftPathSum + rightPathSum + root.Val)
return max(max(leftPathSum+root.Val, rightPathSum+root.Val), 0)
}
func max(a int, b int) int {
if (a >= b) {
return a
}
return b
}
1034 - 2023-11-04 13:27:29 +0300 MSK
Construct Binary Tree from Inorder and Postorder Traversal
Links
Code
func buildTree(inorder []int, postorder []int) *TreeNode {
n := len(postorder)
if n == 0 {
return nil
}
pivotId := 0
for pivotId < n && inorder[pivotId] != postorder[n-1] {
pivotId++
}
root := new(TreeNode)
root.Val = postorder[n-1]
root.Left = buildTree(inorder[:pivotId], postorder[:pivotId])
root.Right = buildTree(inorder[pivotId+1:], postorder[pivotId:n-1])
return root
}
1035 - 2023-11-04 13:27:12 +0300 MSK
Construct Binary Tree from Preorder and Inorder Traversal
Links
Code
func buildTree(preorder []int, inorder []int) *TreeNode {
n := len(inorder)
if n == 0 {
return nil
}
pv := preorder[0]
pi := 0
for pi < n && inorder[pi] != pv {
pi++
}
ans := new(TreeNode)
ans.Val = pv
ans.Left = buildTree(preorder[1:], inorder[:pi])
ans.Right = buildTree(preorder[1+pi:], inorder[pi+1:])
return ans
}
1036 - 2023-11-04 13:26:43 +0300 MSK
Reverse Nodes in k-Group
Links
Code
func reverseKGroup(head *ListNode, k int) *ListNode {
node, cnt := head, 0
for cnt < k {
if node == nil {
return head
}
node = node.Next
cnt++
}
prev := reverseKGroup(node, k)
for cnt > 0 {
next := head.Next
head.Next = prev
prev = head
head = next
cnt--
}
return prev
}
1037 - 2023-11-04 13:25:42 +0300 MSK
Minimum Number of Arrows to Burst Balloons
Links
Code
func findMinArrowShots(points [][]int) int {
// greedy solution
sort.Slice(points, func(i, j int) bool {
return points[i][1] < points[j][1]
})
count := 1
end := points[0][1]
for i := 1; i < len(points); i++ {
if points[i][0] > end {
count++
end = points[i][1]
}
}
return count
}
1038 - 2023-11-04 13:25:15 +0300 MSK
Minimum Window Substring
Links
Code
func minWindow(s string, t string) string {
m := len(s)
n := len(t)
if m == 0 || n == 0 || m < n {
return ""
}
dict := make(map[byte]int)
for i := 0; i < n; i++ {
dict[t[i]]++
}
// required unique chars
required := len(dict)
actual := 0
window := make(map[byte]int)
minSize := math.MaxInt64
start := 0
left, right := 0, 0
for end := 0; end < m; end++ {
c := s[end]
window[c]++
if value, ok := dict[c]; ok {
if value == window[c] {
actual++
}
}
for start <= end && actual == required {
size := end-start+1
if size < minSize {
minSize = size
left = start
right = end
}
rc := s[start]
window[rc]--
if value, ok := dict[rc]; ok {
if value > window[rc] {
actual--
}
}
start++
}
}
if minSize == math.MaxInt64 {
return ""
}
return s[left:right+1]
}
1039 - 2023-11-04 13:24:58 +0300 MSK
Substring with Concatenation of All Words
Links
Code
func findSubstring(s string, words []string) []int {
wordLen := len(words[0])
totalWords := len(words)
mem := make(map[string]int, totalWords)
for _, str := range words {
mem[str] += 1
}
temp := make(map[string]int, totalWords)
var found bool
result := make([]int, 0)
for i:=0; i + wordLen*totalWords <= len(s); {
found = true
temp = make(map[string]int, totalWords)
for j := i; j < i + wordLen*totalWords; j += wordLen {
if _, ok := mem[ s[j:j+wordLen] ]; ok {
temp[ s[j:j+wordLen] ] += 1
} else {
found = false
break
}
}
if found {
for key, _ := range mem {
if val, ok := temp[key]; !ok || val != mem[key]{
i++
found = false
break
}
}
if found {
result = append(result, i)
i += 1
}
} else {
i++
}
}
return result
}
1040 - 2023-11-04 13:23:30 +0300 MSK
Insert Interval
Links
Code
func insert(intervals [][]int, new []int) [][]int {
n := len(intervals)
i := sort.Search(n, func(i int) bool { return intervals[i][0] > new[0] })
j := sort.Search(n, func(j int) bool { return intervals[j][1] > new[1] })
if i >= 1 && new[0] <= intervals[i-1][1] {
new[0] = intervals[i-1][0]
i--
}
if j < n && new[1] >= intervals[j][0] {
new[1] = intervals[j][1]
j++
}
return append(intervals[:i], append([][]int{new}, intervals[j:]...)...)
}
1041 - 2023-11-04 13:22:41 +0300 MSK
Basic Calculator
Links
Code
func calculate(s string) int {
result, _ := calculateFrom(s, 0)
return result
}
func calculateFrom(s string, idFrom int) (result, idEnd int) {
result, currNum, sign := 0, 0, 1
for idEnd = idFrom; idEnd < len(s) && s[idEnd] != ')'; idEnd++ {
switch {
case s[idEnd] >= '0':
currNum = currNum*10 + int(s[idEnd]-'0')
case s[idEnd] == '(':
currNum, idEnd = calculateFrom(s, idEnd+1)
case s[idEnd] == '-' || s[idEnd] == '+':
result, currNum = result+currNum*sign, 0
sign = 44 - int(s[idEnd]) // '-'=45; '+'=43
}
}
return result + currNum*sign, idEnd
}
1042 - 2023-11-04 10:36:18 +0300 MSK
Last Moment Before All Ants Fall Out of a Plank
Links
Code
func getLastMoment(n int, left []int, right []int) int {
return max(slices.Max(append(left, 0)), n - slices.Min(append(right, n)))
}
1043 - 2023-11-04 10:30:12 +0300 MSK
Last Moment Before All Ants Fall Out of a Plank
Links
Code
func getLastMoment(n int, left []int, right []int) int {
maxLeft := 0
for _, val := range left {
if val > maxLeft {
maxLeft = val
}
}
minRight := n
for _, val := range right {
if val < minRight {
minRight = val
}
}
return max(maxLeft, n - minRight)
}
1044 - 2023-11-04 10:29:26 +0300 MSK
Last Moment Before All Ants Fall Out of a Plank
Links
Code
func getLastMoment(n int, left []int, right []int) int {
maxLeft := 0
for _, val := range left {
if val > maxLeft {
maxLeft = val
}
}
minRight := n
for _, val := range right {
if val < minRight {
minRight = val
}
}
return max(maxLeft, n - minRight)
}
1045 - 2023-11-03 15:20:27 +0300 MSK
Kth Smallest Element in a BST
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func kthSmallest(root *TreeNode, k int) int {
heap := binaryheap.NewWithIntComparator()
queue := []*TreeNode{root}
for length := len(queue); length > 0; length = len(queue) {
for i := 0; i < length; i++ {
node := queue[i]
if node == nil {
continue
}
heap.Push(node.Val)
queue = append(queue, node.Left, node.Right)
}
queue = queue[length:]
}
var answer any
for i := 0; i < k; i++ {
answer, _ = heap.Pop()
}
return answer.(int)
}
1046 - 2023-11-03 12:40:06 +0300 MSK
Flatten Binary Tree to Linked List
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func flatten(root *TreeNode) {
if root == nil {
return
}
right := root.Right
root.Right = nil
list := &TreeNode{0, nil, nil}
listTail := flattenNode(root, list)
if right != nil {
flattenNode(right, listTail)
}
}
func flattenNode(node, listTail *TreeNode) *TreeNode {
left, right := node.Left, node.Right
node.Left, node.Right = nil, nil
listTail.Right = node
listTail = listTail.Right
if left != nil {
listTail = flattenNode(left, listTail)
}
if right != nil {
listTail = flattenNode(right, listTail)
}
return listTail
}
1047 - 2023-11-03 12:14:46 +0300 MSK
Build an Array With Stack Operations
Links
Code
func buildArray(target []int, n int) []string {
ops := []string{}
length := len(target)
matchNext, matchNextVal := 0, target[0]
for i := 1; i <= n; i++ {
if i == matchNextVal {
ops = append(ops, "Push")
matchNext += 1
if matchNext == length {
break
}
matchNextVal = target[matchNext]
} else {
ops = append(ops, "Push", "Pop")
}
}
return ops
}
1048 - 2023-11-03 12:13:05 +0300 MSK
Build an Array With Stack Operations
Links
Code
func buildArray(target []int, n int) []string {
ops := []string{}
length := len(target)
matchNext := 0
for i := 1; i <= n; i++ {
if matchNext == length {
break
}
ops = append(ops, "Push")
if i == target[matchNext] {
matchNext += 1
} else {
ops = append(ops, "Pop")
}
}
return ops
}
1049 - 2023-11-02 14:33:34 +0300 MSK
Sort List
Links
Code
func sortList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
if head.Next.Next == nil {
a := head
b := head.Next
if a.Val <= b.Val {
a.Next = b
b.Next = nil
return a
} else {
b.Next = a
a.Next = nil
return b
}
}
slow := head
fast := head
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
}
nextList := slow.Next
slow.Next = nil
list1 := sortList(head)
list2 := sortList(nextList)
dummy := &ListNode{Val: -1, Next: nil}
it := dummy
for list1 != nil && list2 != nil {
if list1.Val <= list2.Val {
it.Next = list1
list1 = list1.Next
} else {
it.Next = list2
list2 = list2.Next
}
it = it.Next
}
if list1 != nil {
it.Next = list1
} else {
it.Next = list2
}
return dummy.Next
}
1050 - 2023-11-02 13:32:46 +0300 MSK
Count Nodes Equal to Average of Subtree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func averageOfSubtree(root *TreeNode) int {
_, _, answer := getAverage(root)
return answer
}
func getAverage(root *TreeNode) (int, int, int) {
if root == nil {
return 0, 0, 0
}
sum, count, validNodes := root.Val, 1, 0
leftSum, leftCount, leftValidNodes := getAverage(root.Left)
rightSum, rightCount, rightValidNodes := getAverage(root.Right)
validNodes += leftValidNodes + rightValidNodes
sum += leftSum + rightSum
count += leftCount + rightCount
if sum / count == root.Val {
validNodes += 1
}
return sum, count, validNodes
}
1051 - 2023-11-01 15:59:19 +0300 MSK
Sum Root to Leaf Numbers
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type queueItem struct {
node *TreeNode
sum int
}
func sumNumbers(root *TreeNode) int {
if root == nil {
return 0
}
queue := []queueItem{queueItem{root, 0}}
sum := 0
for length := len(queue); length > 0; length = len(queue) {
for i := 0; i < length; i++ {
item := queue[i]
if item.node == nil {
continue
}
left, right, newVal := item.node.Left, item.node.Right, item.node.Val + item.sum * 10
if left == nil && right == nil {
sum += newVal
} else {
queue = append(queue, queueItem{left, newVal}, queueItem{right, newVal})
}
}
queue = queue[length:]
}
return sum
}
1052 - 2023-11-01 15:51:19 +0300 MSK
Sum Root to Leaf Numbers
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumNumbers(root *TreeNode) int {
return getSum(root, 0)
}
func getSum(root *TreeNode, parentVal int) int {
if root == nil {
return 0
}
newVal := root.Val + parentVal * 10
if root.Left == nil && root.Right == nil {
return newVal
}
return getSum(root.Left, newVal) + getSum(root.Right, newVal)
}
1053 - 2023-11-01 15:01:54 +0300 MSK
Lowest Common Ancestor of a Binary Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil {
return nil
}
if root == p || root == q {
return root
}
left, right := lowestCommonAncestor(root.Left, p, q), lowestCommonAncestor(root.Right, p, q)
if left != nil && right != nil {
return root
}
if left != nil {
return left
}
return right
}
1054 - 2023-11-01 15:00:05 +0300 MSK
Lowest Common Ancestor of a Binary Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
isAncestorMap := map[int][2]bool{}
dfs(root, p, q, isAncestorMap)
isAncestor := func (node *TreeNode) bool {
if node == nil {
return false
}
hasNodes := isAncestorMap[node.Val]
return hasNodes[0] && hasNodes[1]
}
for {
left, right := root.Left, root.Right
if isAncestor(left) {
root = left
} else if isAncestor(right) {
root = right
} else {
break
}
}
return root
}
func dfs(root, p, q *TreeNode, isAncestorMap map[int][2]bool) (bool, bool) {
if root == nil {
return false, false
}
hasPLeft, hasQLeft := dfs(root.Left, p, q, isAncestorMap)
hasPRight, hasQRight := dfs(root.Right, p, q, isAncestorMap)
hasP, hasQ := hasPLeft || hasPRight, hasQLeft || hasQRight
if root == p {
hasP = true
}
if root == q {
hasQ = true
}
isAncestorMap[root.Val] = [2]bool{hasP, hasQ}
return hasP, hasQ
}
1055 - 2023-11-01 12:34:06 +0300 MSK
Find Mode in Binary Search Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findMode(root *TreeNode) []int {
if root == nil {
return []int{}
}
counter := map[int]int{}
queue := []*TreeNode{root}
for length := len(queue); length > 0; length = len(queue) {
for i := 0; i < length; i++ {
node := queue[i]
if node == nil {
continue
}
left, right, val := node.Left, node.Right, node.Val
if _, ok := counter[val]; ok {
counter[val] += 1
} else {
counter[val] = 1
}
queue = append(queue, left, right)
}
queue = queue[length:]
}
maxCount, answer := 0, []int{}
for key, count := range counter {
if count < maxCount {
continue
}
if count > maxCount {
answer = answer[:0]
maxCount = count
}
answer = append(answer, key)
}
return answer
}
1056 - 2023-11-01 12:32:26 +0300 MSK
Find Mode in Binary Search Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findMode(root *TreeNode) []int {
if root == nil {
return []int{}
}
counter := map[int]int{}
queue := []*TreeNode{root}
for length := len(queue); length > 0; length = len(queue) {
for i := 0; i < length; i++ {
node := queue[i]
if node == nil {
continue
}
if val, ok := counter[node.Val]; ok {
counter[node.Val] = val + 1
} else {
counter[node.Val] = 1
}
queue = append(queue, node.Left, node.Right)
}
queue = queue[length:]
}
maxCount, answer := 0, []int{}
for key, count := range counter {
if count < maxCount {
continue
}
if count > maxCount {
answer = answer[:0]
maxCount = count
}
answer = append(answer, key)
}
return answer
}
1057 - 2023-11-01 12:28:17 +0300 MSK
Find Mode in Binary Search Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findMode(root *TreeNode) []int {
if root == nil {
return []int{}
}
counter := map[int]int{}
dfs(root, counter)
maxCount, answer := 0, []int{}
for key, count := range counter {
if count < maxCount {
continue
}
if count > maxCount {
answer = answer[:0]
maxCount = count
}
answer = append(answer, key)
}
return answer
}
func dfs(root *TreeNode, counter map[int]int) {
if root == nil {
return
}
if _, ok := counter[root.Val]; ok {
counter[root.Val] += 1
} else {
counter[root.Val] = 1
}
dfs(root.Left, counter)
dfs(root.Right, counter)
}
1058 - 2023-11-01 12:20:58 +0300 MSK
Find Mode in Binary Search Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findMode(root *TreeNode) []int {
if root == nil {
return []int{}
}
counter := map[int]int{}
queue := []*TreeNode{root}
for length := len(queue); length > 0; length = len(queue) {
for i := 0; i < length; i++ {
node := queue[i]
if _, ok := counter[node.Val]; ok {
counter[node.Val] += 1
} else {
counter[node.Val] = 1
}
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
queue = queue[length:]
}
maxCount, answer := 0, []int{}
for key, count := range counter {
if count < maxCount {
continue
}
if count > maxCount {
answer = answer[:0]
maxCount = count
}
answer = append(answer, key)
}
return answer
}
1059 - 2023-10-31 19:12:05 +0300 MSK
Validate Binary Search Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type queueItem struct {
node *TreeNode
max *int
min *int
}
func isValidBST(root *TreeNode) bool {
queue := []queueItem{queueItem{root, nil, nil}}
for length := len(queue); length > 0; length = len(queue) {
for i := 0; i < length; i++ {
item := queue[i]
if item.node == nil {
continue
}
node := item.node
if (item.max != nil && node.Val >= *item.max) || (item.min != nil && node.Val <= *item.min) {
return false
}
queue = append(
queue,
queueItem{node.Left, &node.Val, item.min},
queueItem{node.Right, item.max, &node.Val},
)
}
queue = queue[length:]
}
return true
}
1060 - 2023-10-31 19:11:41 +0300 MSK
Validate Binary Search Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type queueItem struct {
node *TreeNode
max *int
min *int
}
func isValidBST(root *TreeNode) bool {
queue := []queueItem{queueItem{root, nil, nil}}
for length := len(queue); length > 0; length = len(queue) {
for i := 0; i < length; i++ {
item := queue[i]
if item.node == nil {
continue
}
node := item.node
if (item.max != nil && node.Val >= *item.max) || (item.min != nil && node.Val <= *item.min) {
return false
}
queue = append(
queue,
queueItem{node.Left, &node.Val, item.min},
queueItem{node.Right, item.max, &node.Val},
)
}
queue = queue[length:]
}
return true
}
1061 - 2023-10-31 18:59:17 +0300 MSK
Validate Binary Search Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isValidBST(root *TreeNode) bool {
if root == nil {
return false
}
return dfs(root.Left, &root.Val, nil) && dfs(root.Right, nil, &root.Val)
}
func dfs(root *TreeNode, max *int, min *int) bool {
if root == nil {
return true
}
if (max != nil && root.Val >= *max) || (min != nil && root.Val <= *min) {
return false
}
return dfs(root.Left, &root.Val, min) && dfs(root.Right, max, &root.Val)
}
1062 - 2023-10-31 18:18:34 +0300 MSK
Maximum Sum Circular Subarray
Links
Code
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func maxSubarraySumCircular(nums []int) int {
var (
max_sum_ending_here = 0
min_sum_ending_here = 0
max_sum_so_far = math.MinInt
min_sum_so_far = math.MaxInt
total = 0
)
for i := 0; i < len(nums); i++ {
num := nums[i]
total += num
max_sum_ending_here += num
min_sum_ending_here += num
max_sum_so_far = max(max_sum_so_far, max_sum_ending_here)
min_sum_so_far = min(min_sum_so_far, min_sum_ending_here)
max_sum_ending_here = max(max_sum_ending_here, 0)
min_sum_ending_here = min(min_sum_ending_here, 0)
}
if max_sum_so_far < 0 {
return max_sum_so_far
}
return max(max_sum_so_far, total - min_sum_so_far)
}
1063 - 2023-10-31 18:15:28 +0300 MSK
Maximum Sum Circular Subarray
Links
Code
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func maxSubarraySumCircular(nums []int) int {
var (
max_sum_ending_here = 0
min_sum_ending_here = 0
max_sum_so_far = math.MinInt
min_sum_so_far = math.MaxInt
total = 0
)
for i := 0; i < len(nums); i++ {
total += nums[i]
max_sum_ending_here += nums[i]
min_sum_ending_here += nums[i]
max_sum_so_far = max(max_sum_so_far, max_sum_ending_here)
min_sum_so_far = min(min_sum_so_far, min_sum_ending_here)
max_sum_ending_here = max(max_sum_ending_here, 0)
min_sum_ending_here = min(min_sum_ending_here, 0)
}
if max_sum_so_far < 0 {
return max_sum_so_far
}
return max(max_sum_so_far, total - min_sum_so_far)
}
1064 - 2023-10-31 18:13:57 +0300 MSK
Maximum Sum Circular Subarray
Links
Code
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func maxSubarraySumCircular(nums []int) int {
var max_sum_ending_here int = 0
var min_sum_ending_here int = 0
var max_sum_so_far int = math.MinInt
var min_sum_so_far int = math.MaxInt
var total = 0
for i := 0; i < len(nums); i++ {
total += nums[i]
max_sum_ending_here += nums[i]
min_sum_ending_here += nums[i]
max_sum_so_far = max(max_sum_so_far, max_sum_ending_here)
min_sum_so_far = min(min_sum_so_far, min_sum_ending_here)
max_sum_ending_here = max(max_sum_ending_here, 0)
min_sum_ending_here = min(min_sum_ending_here, 0)
}
if max_sum_so_far < 0 {
return max_sum_so_far
}
return max(max_sum_so_far, total - min_sum_so_far)
}
1065 - 2023-10-31 11:33:38 +0300 MSK
Find The Original Array of Prefix Xor
Links
Code
func findArray(pref []int) []int {
prev := pref[0]
for i := 1; i < len(pref); i++ {
cur := pref[i]
prev, pref[i] = cur, prev ^ cur
}
return pref
}
1066 - 2023-10-31 11:32:41 +0300 MSK
Find The Original Array of Prefix Xor
Links
Code
func findArray(pref []int) []int {
prev := pref[0]
for i := 1; i < len(pref); i++ {
prev, pref[i] = pref[i], prev ^ pref[i]
}
return pref
}
1067 - 2023-10-30 16:28:30 +0300 MSK
Trapping Rain Water
Links
Code
func trap(height []int) int {
left, right := 0, len(height) - 1
res := 0
leftMax, rightMax := 0, 0
for left < right {
if height[left] < height[right] {
if height[left] >= leftMax {
leftMax = height[left]
} else {
res += (leftMax-height[left])
}
left++
} else {
if height[right] >= rightMax {
rightMax = height[right]
} else {
res += (rightMax-height[right])
}
right--
}
}
return res
}
1068 - 2023-10-30 16:16:38 +0300 MSK
Find First and Last Position of Element in Sorted Array
Links
Code
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def binary_search(nums, target, left):
low, high = 0, len(nums) - 1
index = -1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
index = mid
if left:
high = mid - 1
else:
low = mid + 1
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return index
left_index = binary_search(nums, target, left=True)
right_index = binary_search(nums, target, left=False)
return [left_index, right_index]
1069 - 2023-10-30 16:03:18 +0300 MSK
Minimum Genetic Mutation
Links
Code
func minMutation(startGene string, endGene string, bank []string) int {
if startGene == endGene {
return 0
}
bank = append(bank, startGene)
isMut := func (gene1 string, gene2 string) bool {
foundDiff := false
for i := 0; i < len(gene1); i++ {
if gene1[i] == gene2[i] {
continue
}
if foundDiff {
return false
}
foundDiff = true
}
return foundDiff
}
graph := map[string][]string{}
for i, gene1 := range bank {
for _, gene2 := range bank[i+1:] {
if !isMut(gene1, gene2) {
continue
}
if _, ok := graph[gene1]; !ok {
graph[gene1] = []string{}
}
if _, ok := graph[gene2]; !ok {
graph[gene2] = []string{}
}
graph[gene1] = append(graph[gene1], gene2)
graph[gene2] = append(graph[gene2], gene1)
}
}
queue, ok := graph[endGene]
if !ok {
return -1
}
delete(graph, endGene)
num := 1
for length := len(queue); length > 0; length = len(queue) {
for i := 0; i < length; i++ {
gene := queue[i]
muts, ok := graph[gene]
if !ok {
continue
}
if gene == startGene {
return num
}
delete(graph, gene)
queue = append(queue, muts...)
}
num += 1
queue = queue[length:]
}
return -1
}
1070 - 2023-10-30 15:58:41 +0300 MSK
Minimum Genetic Mutation
Links
Code
func minMutation(startGene string, endGene string, bank []string) int {
if startGene == endGene {
return 0
}
bank = append(bank, startGene)
isMut := func (gene1 string, gene2 string) bool {
foundDiff := false
for i := 0; i < len(gene1); i++ {
if gene1[i] == gene2[i] {
continue
}
if foundDiff {
return false
}
foundDiff = true
}
return foundDiff
}
graph := map[string][]string{}
for i, gene1 := range bank {
for _, gene2 := range bank[i+1:] {
if !isMut(gene1, gene2) {
continue
}
if _, ok := graph[gene1]; !ok {
graph[gene1] = []string{}
}
if _, ok := graph[gene2]; !ok {
graph[gene2] = []string{}
}
graph[gene1] = append(graph[gene1], gene2)
graph[gene2] = append(graph[gene2], gene1)
}
}
queue, ok := graph[endGene]
if !ok {
return -1
}
visited := map[string]struct{}{endGene: struct{}{}}
num := 1
for length := len(queue); length > 0; length = len(queue) {
for i := 0; i < length; i++ {
gene := queue[i]
if _, ok := visited[gene]; ok {
continue
}
if gene == startGene {
return num
}
visited[gene] = struct{}{}
queue = append(queue, graph[gene]...)
}
num += 1
queue = queue[length:]
}
return -1
}
1071 - 2023-10-30 14:32:47 +0300 MSK
Binary Tree Zigzag Level Order Traversal
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func zigzagLevelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
queue, answer := []*TreeNode{root}, [][]int{}
ltr := true
for length := len(queue); length != 0; length = len(queue) {
answerRow := []int{}
for i := 0; i < length; i++ {
node := queue[i]
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
answerRow = append(answerRow, node.Val)
}
if !ltr {
slices.Reverse(answerRow)
}
queue = queue[length:]
ltr = !ltr
answer = append(answer, answerRow)
}
return answer
}
1072 - 2023-10-30 14:31:36 +0300 MSK
Binary Tree Zigzag Level Order Traversal
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func zigzagLevelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
queue, answer := []*TreeNode{root}, [][]int{}
ltr := true
for length := len(queue); length != 0; length = len(queue) {
answerRow := []int{}
for i := 0; i < length; i++ {
node := queue[i]
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
if ltr {
answerRow = append(answerRow, node.Val)
} else {
answerRow = append([]int{node.Val}, answerRow...)
}
}
queue = queue[length:]
ltr = !ltr
answer = append(answer, answerRow)
}
return answer
}
1073 - 2023-10-30 14:14:48 +0300 MSK
Binary Tree Zigzag Level Order Traversal
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func zigzagLevelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
queue, answer := []*TreeNode{root}, [][]int{}
leftToRight := true
for length := len(queue); length != 0; length = len(queue) {
answerRow := []int{}
for i := 0; i < length; i++ {
node := queue[0]
queue = queue[1:]
answerRow = append(answerRow, node.Val)
if left := node.Left; left != nil {
queue = append(queue, left)
}
if right := node.Right; right != nil {
queue = append(queue, right)
}
}
if !leftToRight {
slices.Reverse(answerRow)
}
leftToRight = !leftToRight
answer = append(answer, answerRow)
}
return answer
}
1074 - 2023-10-30 13:59:23 +0300 MSK
Binary Tree Level Order Traversal
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func levelOrder(root *TreeNode) [][]int {
queue, answer := []*TreeNode{root}, [][]int{}
for length := len(queue); length != 0; length = len(queue) {
answerRow := []int{}
for i := 0; i < length; i++ {
node := queue[0]
queue = queue[1:]
if node == nil {
continue
}
answerRow = append(answerRow, node.Val)
queue = append(queue, node.Left, node.Right)
}
if len(answerRow) != 0 {
answer = append(answer, answerRow)
}
}
return answer
}
1075 - 2023-10-30 13:51:15 +0300 MSK
Binary Tree Level Order Traversal
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
stack, answer := []*TreeNode{root}, [][]int{}
for length := len(stack); length != 0; length = len(stack) {
answerRow := []int{}
for i := 0; i < length; i++ {
node := stack[0]
answerRow = append(answerRow, node.Val)
stack = stack[1:]
if left := node.Left; left != nil {
stack = append(stack, node.Left)
}
if right := node.Right; right != nil {
stack = append(stack, node.Right)
}
}
answer = append(answer, answerRow)
}
return answer
}
1076 - 2023-10-30 13:39:35 +0300 MSK
Binary Tree Right Side View
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rightSideView(root *TreeNode) []int {
if root == nil {
return []int{}
}
queue, answer := []*TreeNode{root}, []int{}
for length := len(queue); length != 0; length = len(queue) {
for i := 0; i < length; i++ {
node := queue[0]
queue = queue[1:]
if i == length - 1 {
answer = append(answer, node.Val)
}
if left := node.Left; left != nil {
queue = append(queue, left)
}
if right := node.Right; right != nil {
queue = append(queue, right)
}
}
}
return answer
}
1077 - 2023-10-30 13:33:19 +0300 MSK
Average of Levels in Binary Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func averageOfLevels(root *TreeNode) []float64 {
if root == nil {
return []float64{}
}
queue, answer := []*TreeNode{root}, []float64{}
for length := len(queue); length != 0; length = len(queue) {
av := 0
for i := 0; i < length; i++ {
node := queue[0]
queue = queue[1:]
av += node.Val
if left := node.Left; left != nil {
queue = append(queue, left)
}
if right := node.Right; right != nil {
queue = append(queue, right)
}
}
answer = append(answer, float64(av) / float64(length))
}
return answer
}
1078 - 2023-10-30 13:26:37 +0300 MSK
Average of Levels in Binary Tree
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func averageOfLevels(root *TreeNode) []float64 {
if root == nil {
return []float64{}
}
qCur, qNext, answer := []*TreeNode{root}, []*TreeNode{}, []float64{}
for len(qCur) != 0 {
av := 0
for _, node := range qCur {
av += node.Val
if left := node.Left; left != nil {
qNext = append(qNext, left)
}
if right := node.Right; right != nil {
qNext = append(qNext, right)
}
}
answer = append(answer, float64(av) / float64(len(qCur)))
qCur = qCur[:0]
qCur, qNext = qNext, qCur
}
return answer
}
1079 - 2023-10-30 13:17:08 +0300 MSK
Binary Tree Right Side View
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rightSideView(root *TreeNode) []int {
if root == nil {
return []int{}
}
q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}
for len(q_cur) != 0 {
for _, node := range q_cur {
if left := node.Left; left != nil {
q_next = append(q_next, left)
}
if right := node.Right; right != nil {
q_next = append(q_next, right)
}
}
answer = append(answer, q_cur[len(q_cur) - 1].Val)
q_cur = q_cur[:0]
q_cur, q_next = q_next, q_cur
}
return answer
}
1080 - 2023-10-30 13:16:47 +0300 MSK
Binary Tree Right Side View
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rightSideView(root *TreeNode) []int {
if root == nil {
return []int{}
}
q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}
for len(q_cur) != 0 {
var last int
for _, node := range q_cur {
if left := node.Left; left != nil {
q_next = append(q_next, left)
}
if right := node.Right; right != nil {
q_next = append(q_next, right)
}
last = node.Val
}
answer = append(answer, last)
q_cur = q_cur[:0]
q_cur, q_next = q_next, q_cur
}
return answer
}
1081 - 2023-10-30 13:16:38 +0300 MSK
Binary Tree Right Side View
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rightSideView(root *TreeNode) []int {
if root == nil {
return []int{}
}
q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}
for len(q_cur) != 0 {
var last int
for _, node := range q_cur {
if left := node.Left; left != nil {
q_next = append(q_next, left)
}
if right := node.Right; right != nil {
q_next = append(q_next, right)
}
last = node.Val
}
answer = append(answer, last)
q_cur = q_cur[:0]
q_cur, q_next = q_next, q_cur
}
return answer
}
1082 - 2023-10-30 13:13:00 +0300 MSK
Binary Tree Right Side View
Links
Code
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rightSideView(root *TreeNode) []int {
if root == nil {
return []int{}
}
q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}
for length := len(q_cur); length > 0; length = len(q_cur) {
for _, node := range q_cur {
if left := node.Left; left != nil {
q_next = append(q_next, left)
}
if right := node.Right; right != nil {
q_next = append(q_next, right)
}
}
answer = append(answer, q_cur[length - 1].Val)
q_cur = q_cur[:0]
q_cur, q_next = q_next, q_cur
}
return answer
}
1083 - 2023-10-30 12:17:05 +0300 MSK
Binary Tree Right Side View
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
q_cur, q_next, answer = deque(), deque(), []
q_cur.append(root)
while q_cur:
last_val = None
while q_cur:
node = q_cur.popleft()
last_val = node.val
if node.left:
q_next.append(node.left)
if node.right:
q_next.append(node.right)
q_cur, q_next = q_next, q_cur
answer.append(last_val)
return answer
1084 - 2023-10-30 12:10:35 +0300 MSK
Binary Tree Right Side View
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
cur, nxt = [root], []
answer = []
while cur:
last_node = cur.pop()
if last_node.right:
nxt.append(last_node.right)
if last_node.left:
nxt.append(last_node.left)
answer.append(last_node.val)
while cur:
node = cur.pop()
if node.right:
nxt.append(node.right)
if node.left:
nxt.append(node.left)
cur.clear()
nxt.reverse()
cur, nxt = nxt, cur
return answer
1085 - 2023-10-30 10:51:12 +0300 MSK
Sort Integers by The Number of 1 Bits
Links
Code
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
return tuple(num for num in sorted(arr, key=lambda num: (num.bit_count(), num)))
1086 - 2023-10-29 19:36:33 +0300 MSK
Poor Pigs
Links
Code
class Solution:
def poorPigs(self, buckets: int, a: int, b: int) -> int:
pigs = 0
while (b / a + 1) ** pigs < buckets:
pigs += 1
return pigs
1087 - 2023-10-28 17:51:04 +0300 MSK
Count Vowels Permutation
Links
Code
class Solution:
def countVowelPermutation(self, n: int) -> int:
MOD = 10**9 + 7
a, e, i, o, u = 1, 1, 1, 1, 1
for _ in range(1, n):
a_next = e
e_next = (a + i) % MOD
i_next = (a + e + o + u) % MOD
o_next = (i + u) % MOD
u_next = a
a, e, i, o, u = a_next, e_next, i_next, o_next, u_next
return (a + e + i + o + u) % MOD
1088 - 2023-10-27 17:47:50 +0300 MSK
Longest Palindromic Substring
Links
Code
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
dp = [[False] * n for _ in range(n)]
ans = [0, 0]
for i in range(n):
dp[i][i] = True
for i in range(n - 1):
if s[i] == s[i + 1]:
dp[i][i + 1] = True
ans = [i, i + 1]
for diff in range(2, n):
for i in range(n - diff):
j = i + diff
if s[i] == s[j] and dp[i + 1][j - 1]:
dp[i][j] = True
ans = [i, j]
i, j = ans
return s[i:j + 1]
1089 - 2023-10-26 23:07:22 +0300 MSK
Binary Trees With Factors
Links
Code
MOD = 10**9 + 7
class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
arr.sort()
s = set(arr)
dp = {x: 1 for x in arr}
for i in arr:
for j in arr:
if j > i**0.5:
break
if i % j == 0 and i // j in s:
if i // j == j:
dp[i] += dp[j] * dp[j]
else:
dp[i] += dp[j] * dp[i // j] * 2
dp[i] %= MOD
return sum(dp.values()) % MOD
1090 - 2023-10-25 13:37:39 +0300 MSK
Design Add and Search Words Data Structure
Links
Code
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
cur = self.root
for char in word:
cur = cur.children.setdefault(char, TrieNode())
cur.is_word = True
def search(self, word: str) -> bool:
cur, nxt = [self.root], []
for char in word:
if not cur:
return False
if char == ".":
for node in cur:
nxt.extend(node.children.values())
else:
for node in cur:
if char in node.children:
nxt.append(node.children[char])
cur.clear()
cur, nxt = nxt, cur
return any(node.is_word for node in cur)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
1091 - 2023-10-25 11:31:06 +0300 MSK
K-th Symbol in Grammar
Links
Code
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
def get(row: int, column: int) -> int:
if column == 0 or column == 1:
return column
prev_row_length = 2 ** (row - 1)
if column >= prev_row_length:
return 1 ^ get(row - 1, column - prev_row_length)
return get(row - 1, column)
return get(n - 1, k - 1)
# 0
# 0 1
# 0 1 1 0
# 0 1 1 0 1 0 0 1
# 0 1 1 0 1 0 0 1
1092 - 2023-10-24 14:55:16 +0300 MSK
Find Largest Value in Each Tree Row
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
largest = []
cur, nxt = [root], []
cur_val = None
while cur or nxt:
while cur:
node = cur.pop()
if cur_val is None or node.val > cur_val:
cur_val = node.val
if node.left:
nxt.append(node.left)
if node.right:
nxt.append(node.right)
largest.append(cur_val)
cur.clear()
cur_val = None
cur, nxt = nxt, cur
return largest
1093 - 2023-10-23 12:26:07 +0300 MSK
Power of Four
Links
Code
class Solution:
def isPowerOfFour(self, n: int) -> bool:
# Check if the number is greater than zero and is a power of two
if n > 0 and (n & (n - 1)) == 0:
# Check if the number is of the form 4^x
return n & 0x55555555 == n
else:
return False
1094 - 2023-10-22 13:57:47 +0300 MSK
Maximum Score of a Good Subarray
Links
Code
class Solution:
def maximumScore(self, nums: List[int], k: int) -> int:
n = len(nums)
left = k
right = k
ans = nums[k]
curr_min = nums[k]
while left > 0 or right < n - 1:
if (nums[left - 1] if left else 0) < (nums[right + 1] if right < n - 1 else 0):
right += 1
curr_min = min(curr_min, nums[right])
else:
left -= 1
curr_min = min(curr_min, nums[left])
ans = max(ans, curr_min * (right - left + 1))
return ans
1095 - 2023-10-21 14:20:53 +0300 MSK
Constrained Subsequence Sum
Links
Code
import heapq
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
heap = [(-nums[0], 0)]
ans = nums[0]
for i in range(1, len(nums)):
while i - heap[0][1] > k:
heapq.heappop(heap)
curr = max(0, -heap[0][0]) + nums[i]
ans = max(ans, curr)
heapq.heappush(heap, (-curr, i))
return ans
1096 - 2023-10-20 16:11:39 +0300 MSK
Flatten Nested List Iterator
Links
Code
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def isInteger(self) -> bool:
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# """
#
# def getInteger(self) -> int:
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# """
#
# def getList(self) -> [NestedInteger]:
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# """
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
self.get_next = self.get_next_gen(nestedList)
self.next_val = next(self.get_next, None)
def get_next_gen(self, nestedList: List[NestedInteger]) -> Generator[None, None, int]:
for ni in nestedList:
if ni.isInteger():
yield ni.getInteger()
else:
yield from self.get_next_gen(ni.getList())
def next(self) -> int:
answer, self.next_val = self.next_val, next(self.get_next, None)
return answer
def hasNext(self) -> bool:
return self.next_val is not None
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
1097 - 2023-10-20 16:06:36 +0300 MSK
Flatten Nested List Iterator
Links
Code
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def isInteger(self) -> bool:
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# """
#
# def getInteger(self) -> int:
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# """
#
# def getList(self) -> [NestedInteger]:
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# """
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
self.list = []
self.flatten(self.list, nestedList)
self.cur = 0
self.length = len(self.list)
def flatten(self, flatList: List[int], nestedList: List[NestedInteger]):
for ni in nestedList:
if ni.isInteger():
flatList.append(ni.getInteger())
else:
self.flatten(flatList, ni.getList())
def next(self) -> int:
answer = self.list[self.cur]
self.cur += 1
return answer
def hasNext(self) -> bool:
return self.cur < self.length
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
1098 - 2023-10-19 17:09:46 +0300 MSK
Backspace String Compare
Links
Code
class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
i1, i2 = len(s) - 1, len(t) - 1
skip1, skip2 = 0, 0
while i1 >= 0 or i2 >= 0:
char1, char2 = s[i1] if i1 >= 0 else "", t[i2] if i2 >= 0 else ""
if char1 == "#":
i1 -= 1
skip1 += 1
elif char2 == "#":
i2 -= 1
skip2 += 1
elif skip1 > 0:
i1 -= 1
skip1 -= 1
elif skip2 > 0:
i2 -= 1
skip2 -= 1
elif char1 != char2:
return False
else:
i1 -= 1
i2 -= 1
return True
1099 - 2023-10-18 19:38:53 +0300 MSK
Parallel Courses III
Links
Code
class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
graph = defaultdict(list)
indegree = [0] * n
for (x, y) in relations:
graph[x - 1].append(y - 1)
indegree[y - 1] += 1
queue = deque()
max_time = [0] * n
for node in range(n):
if indegree[node] == 0:
queue.append(node)
max_time[node] = time[node]
while queue:
node = queue.popleft()
for neighbor in graph[node]:
max_time[neighbor] = max(max_time[neighbor], max_time[node] + time[neighbor])
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
queue.append(neighbor)
return max(max_time)
1100 - 2023-10-17 18:45:21 +0300 MSK
Validate Binary Tree Nodes
Links
Code
class Solution:
def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
parents = [-1] * n
for i in range(n):
left, right = leftChild[i], rightChild[i]
left_valid, right_valid = left != -1, right != -1
if (left_valid and parents[left] != -1) or (
right_valid and parents[right] != -1
):
return False
if left_valid:
parents[left] = i
if right_valid:
parents[right] = i
parent = parents[i]
if parent != -1 and (parent == left or parent == right):
return False
root = None
for i, node in enumerate(parents):
if node == -1 and root is not None:
return False
if node == -1:
root = i
if root is None:
return False
to_visit = [root]
visited = set()
while to_visit:
node = to_visit.pop()
if node in visited:
return False
visited.add(node)
left, right = leftChild[node], rightChild[node]
if left != -1:
to_visit.append(left)
if right != -1:
to_visit.append(right)
return len(visited) == n
1101 - 2023-10-16 20:32:07 +0300 MSK
Pascal’s Triangle II
Links
Code
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
cur, prev = [], [1]
row = 0
while row < rowIndex:
cur.append(1)
for i in range(1, len(prev)):
cur.append(prev[i] + prev[i-1])
cur.append(1)
prev.clear()
cur, prev = prev, cur
row += 1
return prev
1102 - 2023-10-15 13:05:28 +0300 MSK
Number of Ways to Stay in the Same Place After Some Steps
Links
Code
class Solution:
def numWays(self, steps: int, arrLen: int) -> int:
@cache
def dp(curr, remain):
if remain == 0:
if curr == 0:
return 1
return 0
ans = dp(curr, remain - 1)
if curr > 0:
ans = (ans + dp(curr - 1, remain - 1)) % MOD
if curr < arrLen - 1:
ans = (ans + dp(curr + 1, remain - 1)) % MOD
return ans
MOD = 10 ** 9 + 7
return dp(0, steps)
1103 - 2023-10-14 19:53:26 +0300 MSK
Painting the Walls
Links
Code
class Solution:
def paintWalls(self, cost: List[int], time: List[int]) -> int:
@cache
def dp(i, remain):
if remain <= 0:
return 0
if i == n:
return inf
paint = cost[i] + dp(i + 1, remain - 1 - time[i])
dont_paint = dp(i + 1, remain)
return min(paint, dont_paint)
n = len(cost)
return dp(0, n)
1104 - 2023-10-14 10:14:40 +0300 MSK
Min Cost Climbing Stairs
Links
Code
class Solution:
def minCostClimbingStairs(self, cost):
n = len(cost)
dp = [0] * n
dp[0] = cost[0]
dp[1] = cost[1]
for i in range(2, n):
dp[i] = cost[i] + min(dp[i-1], dp[i-2])
return min(dp[n-1], dp[n-2])
1105 - 2023-10-12 12:09:45 +0300 MSK
Find in Mountain Array
Links
Code
class Solution:
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
# Save the length of the mountain array
length = mountain_arr.length()
# 1. Find the index of the peak element
low = 1
high = length - 2
while low != high:
test_index = (low + high) // 2
if mountain_arr.get(test_index) < mountain_arr.get(test_index + 1):
low = test_index + 1
else:
high = test_index
peak_index = low
# 2. Search in the strictly increasing part of the array
low = 0
high = peak_index
while low != high:
test_index = (low + high) // 2
if mountain_arr.get(test_index) < target:
low = test_index + 1
else:
high = test_index
# Check if the target is present in the strictly increasing part
if mountain_arr.get(low) == target:
return low
# 3. Otherwise, search in the strictly decreasing part
low = peak_index + 1
high = length - 1
while low != high:
test_index = (low + high) // 2
if mountain_arr.get(test_index) > target:
low = test_index + 1
else:
high = test_index
# Check if the target is present in the strictly decreasing part
if mountain_arr.get(low) == target:
return low
# Target is not present in the mountain array
return -1
1106 - 2023-10-11 16:06:35 +0300 MSK
Number of Flowers in Full Bloom
Links
Code
class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:
flowers.sort()
sorted_people = sorted(people)
dic = {}
heap = []
i = 0
for person in sorted_people:
while i < len(flowers) and flowers[i][0] <= person:
heapq.heappush(heap, flowers[i][1])
i += 1
while heap and heap[0] < person:
heapq.heappop(heap)
dic[person] = len(heap)
return [dic[x] for x in people]
1107 - 2023-10-10 08:23:28 +0300 MSK
Minimum Number of Operations to Make Array Continuous
Links
Code
class Solution:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
ans = n
new_nums = sorted(set(nums))
for i in range(len(new_nums)):
left = new_nums[i]
right = left + n - 1
j = bisect_right(new_nums, right)
count = j - i
ans = min(ans, n - count)
return ans
1108 - 2023-10-09 14:15:25 +0300 MSK
Find First and Last Position of Element in Sorted Array
Links
Code
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def binary_search(nums, target, left):
low, high = 0, len(nums) - 1
index = -1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
index = mid
if left:
high = mid - 1
else:
low = mid + 1
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return index
left_index = binary_search(nums, target, left=True)
right_index = binary_search(nums, target, left=False)
return [left_index, right_index]
1109 - 2023-10-08 10:39:44 +0300 MSK
Max Dot Product of Two Subsequences
Links
Code
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
@cache
def dp(i, j):
if i == len(nums1) or j == len(nums2):
return 0
use = nums1[i] * nums2[j] + dp(i + 1, j + 1)
return max(use, dp(i + 1, j), dp(i, j + 1))
if max(nums1) < 0 and min(nums2) > 0:
return max(nums1) * min(nums2)
if min(nums1) > 0 and max(nums2) < 0:
return min(nums1) * max(nums2)
return dp(0, 0)
1110 - 2023-10-07 19:48:10 +0300 MSK
Build Array Where You Can Find The Maximum Exactly K Comparisons
Links
Code
class Solution:
def numOfArrays(self, n: int, m: int, k: int) -> int:
@cache
def dp(i, max_so_far, remain):
if i == n:
if remain == 0:
return 1
return 0
ans = (max_so_far * dp(i + 1, max_so_far, remain)) % MOD
for num in range(max_so_far + 1, m + 1):
ans = (ans + dp(i + 1, num, remain - 1)) % MOD
return ans
MOD = 10 ** 9 + 7
return dp(0, 0, k)
1111 - 2023-10-06 12:24:39 +0300 MSK
Integer Break
Links
Code
class Solution:
def integerBreak(self, n: int) -> int:
if n < 4:
return n - 1
@cache
def dp(num: int) -> int:
if num <= 3:
return num
ans = num
for i in range(2, num):
ans = max(ans, i * dp(num - i))
return ans
return dp(n)
1112 - 2023-10-06 12:24:09 +0300 MSK
Integer Break
Links
Code
class Solution:
def integerBreak(self, n: int) -> int:
@cache
def dp(num: int) -> int:
if num <= 3:
return num
ans = num
for i in range(2, num):
ans = max(ans, i * dp(num - i))
return ans
return dp(n) if n > 3 else n - 1
1113 - 2023-10-05 09:46:37 +0300 MSK
Majority Element II
Links
Code
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
nums.sort()
threshold = len(nums) // 3
cur_num, cur_count = nums[0], 1
answer = []
for num in nums[1:]:
if num == cur_num:
cur_count += 1
continue
if cur_count > threshold:
answer.append(cur_num)
cur_num, cur_count = num, 1
if cur_count > threshold:
answer.append(cur_num)
return answer
1114 - 2023-10-04 09:00:01 +0300 MSK
Design HashMap
Links
Code
class ListNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
class MyHashMap:
def __init__(self):
self.size = 1000
self.table = [None] * self.size
def _index(self, key: int) -> int:
return key % self.size
def put(self, key: int, value: int) -> None:
idx = self._index(key)
if not self.table[idx]:
self.table[idx] = ListNode(key, value)
return
current = self.table[idx]
while current:
if current.key == key:
current.value = value
return
if not current.next:
current.next = ListNode(key, value)
return
current = current.next
def get(self, key: int) -> int:
idx = self._index(key)
current = self.table[idx]
while current:
if current.key == key:
return current.value
current = current.next
return -1
def remove(self, key: int) -> None:
idx = self._index(key)
current = self.table[idx]
if not current:
return
if current.key == key:
self.table[idx] = current.next
return
while current.next:
if current.next.key == key:
current.next = current.next.next
return
current = current.next
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
1115 - 2023-10-04 08:57:26 +0300 MSK
Design HashMap
Links
Code
class MyHashMap:
def __init__(self):
self.data = [None] * 1000001
def put(self, key: int, val: int) -> None:
self.data[key] = val
def get(self, key: int) -> int:
val = self.data[key]
return -1 if val is None else val
def remove(self, key: int) -> None:
self.data[key] = None
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
1116 - 2023-10-03 09:14:03 +0300 MSK
Number of Good Pairs
Links
Code
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
counter = Counter(nums)
return sum((count ** 2 - count) // 2 for count in counter.values() if count > 1)
1117 - 2023-10-03 09:13:40 +0300 MSK
Number of Good Pairs
Links
Code
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
return sum((count ** 2 - count) // 2 for count in Counter(nums).values() if count > 1)
1118 - 2023-10-03 09:13:11 +0300 MSK
Number of Good Pairs
Links
Code
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
counter = Counter(nums)
return sum((count ** 2 - count) // 2 for count in counter.values() if count > 1)
1119 - 2023-10-02 15:20:53 +0300 MSK
Remove Colored Pieces if Both Neighbors are the Same Color
Links
Code
class Solution:
def winnerOfGame(self, colors: str) -> bool:
cur_char, cur_conseq = colors[0], 1
moves = {"A": 0, "B": 0}
for char in colors[1:]:
if char == cur_char:
cur_conseq += 1
else:
moves[cur_char] += max(0, cur_conseq - 2)
cur_char, cur_conseq = char, 1
if cur_conseq > 2:
moves[cur_char] += cur_conseq - 2
return moves["A"] > moves["B"]
1120 - 2023-10-01 16:29:08 +0300 MSK
Reverse Words in a String III
Links
Code
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(map(lambda word: word[::-1], s.split()))
1121 - 2023-09-30 10:17:26 +0300 MSK
Merge Intervals
Links
Code
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda item: item[0])
merged = []
for start, end in intervals:
# if the list of merged intervals is empty or if the current
# interval does not overlap with the previous, simply append it.
if not merged or merged[-1][1] < start:
merged.append([start, end])
else:
# otherwise, there is overlap, so we merge the current and previous
# intervals.
merged[-1][1] = max(merged[-1][1], end)
return merged
1122 - 2023-09-30 10:09:04 +0300 MSK
132 Pattern
Links
Code
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
if len(nums) < 3:
return False
min_array = [-1] * len(nums)
min_array[0] = nums[0]
for i in range(1, len(nums)):
min_array[i] = min(min_array[i - 1], nums[i])
k = len(nums)
for j in range(len(nums) - 1, -1, -1):
if nums[j] <= min_array[j]:
continue
while k < len(nums) and nums[k] <= min_array[j]:
k += 1
if k < len(nums) and nums[k] < nums[j]:
return True
k -= 1
nums[k] = nums[j]
return False
1123 - 2023-09-30 10:05:56 +0300 MSK
132 Pattern
Links
Code
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
if len(nums) < 3:
return False
stack = []
min_array = [-1] * len(nums)
min_array[0] = nums[0]
for i in range(1, len(nums)):
min_array[i] = min(min_array[i - 1], nums[i])
for j in reversed(range(len(nums))):
if nums[j] <= min_array[j]:
continue
while stack and stack[-1] <= min_array[j]:
stack.pop()
if stack and stack[-1] < nums[j]:
return True
stack.append(nums[j])
return False
1124 - 2023-09-29 08:36:09 +0300 MSK
Monotonic Array
Links
Code
class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
length = len(nums)
if length < 3:
return True
is_increasing = None
for i in range(1, length):
cur, prev = nums[i], nums[i-1]
if cur == prev:
continue
is_increasing_cur = cur > prev
if is_increasing is None:
is_increasing = is_increasing_cur
continue
if is_increasing and not is_increasing_cur or (
not is_increasing and is_increasing_cur
):
return False
return True
1125 - 2023-09-28 10:17:33 +0300 MSK
Sort Array By Parity
Links
Code
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
left, right = 0, len(nums) - 1
while left < right:
while left < right and nums[left] % 2 == 0:
left += 1
while left < right and nums[right] % 2 == 1:
right -= 1
nums[left], nums[right] = nums[right], nums[left]
return nums
1126 - 2023-09-28 10:13:16 +0300 MSK
Sort Array By Parity
Links
Code
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
length = len(nums)
left, right = 0, length - 1
answer = [None] * length
for num in nums:
if num % 2 == 0:
answer[left] = num
left += 1
else:
answer[right] = num
right -= 1
return answer
1127 - 2023-09-27 18:11:20 +0300 MSK
Decoded String at Index
Links
Code
class Solution:
def decodeAtIndex(self, s: str, k: int) -> str:
length = 0
i = 0
while length < k:
if s[i].isdigit():
length *= int(s[i])
else:
length += 1
i += 1
for j in range(i-1, -1, -1):
char = s[j]
if char.isdigit():
length //= int(char)
k %= length
else:
if k == 0 or k == length:
return char
length -= 1
1128 - 2023-09-26 13:43:09 +0300 MSK
Remove Duplicate Letters
Links
Code
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
stack = []
seen = set()
last_occ = {char: i for i, char in enumerate(s)}
for i, char in enumerate(s):
if char in seen:
continue
while stack and char < stack[-1] and i < last_occ[stack[-1]]:
seen.discard(stack.pop())
seen.add(char)
stack.append(char)
return ''.join(stack)
1129 - 2023-09-25 09:17:00 +0300 MSK
Find Minimum in Rotated Sorted Array
Links
Code
class Solution:
def findMin(self, nums: List[int]) -> int:
length = len(nums)
if length == 1:
return nums[0]
first, last = nums[0], nums[-1]
if first < last:
return first
left, right = 0, length - 1
while left <= right:
mid = left + (right - left) // 2
left_num = nums[mid - 1] if mid > 0 else first
mid_num = nums[mid]
right_num = nums[mid + 1] if mid + 1 < length else last
if left_num > mid_num <= right_num:
return mid_num
if left_num > mid_num or (left_num <= mid_num and mid_num >= first):
left = mid + 1
else:
right = mid
return nums[left]
1130 - 2023-09-25 08:28:38 +0300 MSK
Find the Difference
Links
Code
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
return chr(reduce(operator.xor, (ord(char) for char in chain(s, t))))
1131 - 2023-09-25 08:26:39 +0300 MSK
Find the Difference
Links
Code
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
count = Counter(s)
for char in t:
count[char] -= 1
if count[char] == -1:
return char
1132 - 2023-09-24 14:37:54 +0300 MSK
Bitwise AND of Numbers Range
Links
Code
class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
shift = 0
while left < right:
left >>= 1
right >>= 1
shift += 1
return left << shift
1133 - 2023-09-24 13:28:55 +0300 MSK
Container With Most Water
Links
Code
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
maxArea = 0
while left < right:
currentArea = min(height[left], height[right]) * (right - left)
if currentArea > maxArea:
maxArea = currentArea
if height[left] < height[right]:
left += 1
else:
right -= 1
return maxArea
1134 - 2023-09-24 13:26:28 +0300 MSK
Max Points on a Line
Links
Code
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
lines = defaultdict(set)
length = len(points)
if length < 3:
return length
for i in range(length):
x1, y1 = points[i]
for j in range(i + 1, length):
x2, y2 = points[j]
k1, k2 = None, None
if y1 == y2:
k2 = y1
elif x1 == x2:
k1 = x1
else:
k1 = (y2 - y1) / (x2 - x1)
k2 = y1 - k1 * x1
lines[(k1, k2)].update(((x1, y1), (x2, y2)))
return max((len(points) for points in lines.values()), default=0)
1135 - 2023-09-24 13:00:11 +0300 MSK
Candy
Links
Code
class Solution:
def candy(self, ratings: List[int]) -> int:
child_count = len(ratings)
candies = [1] * child_count
for i in range(1, child_count):
if ratings[i] > ratings[i-1]:
candies[i] = candies[i-1] + 1
for i in reversed(range(child_count - 1)):
if ratings[i] > ratings[i+1]:
candies[i] = max(candies[i], candies[i+1] + 1)
return sum(candies)
1136 - 2023-09-24 12:59:51 +0300 MSK
Longest Substring Without Repeating Characters
Links
Code
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length = len(s)
if length < 2:
return length
max_length, left, charset = 1, 0, set([s[0]])
for right in range(1, length):
letter = s[right]
if letter not in charset:
charset.add(letter)
continue
this_length = right - left
if this_length > max_length:
max_length = this_length
while letter in charset:
charset.remove(s[left])
left += 1
charset.add(letter)
return max(max_length, length - left)
1137 - 2023-09-24 12:59:24 +0300 MSK
Populating Next Right Pointers in Each Node II
Links
Code
from collections import deque
class Solution:
def connect(self, root: 'Node') -> 'Node':
# Edge case - If the root is None, then return None
if root is None:
return None
# Create a queue and enqueue the root node
q = deque([root])
# Traverse the tree level by level
while q:
# Get the number of nodes of the current level
level_size = len(q)
# Process the nodes of the current level
for i in range(level_size):
# Dequeue a node from the front of the queue
node = q.popleft()
# Assign the next pointer of the node
if i < level_size - 1:
node.next = q[0]
# Enqueue the children of the node (if any)
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
# Return the root node
return root
1138 - 2023-09-24 12:56:43 +0300 MSK
Binary Search Tree Iterator
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
def generate(node: TreeNode) -> int:
if not node:
return
yield from generate(node.left)
yield node
yield from generate(node.right)
self._generate = generate(root)
self._next = next(self._generate)
def next(self) -> int:
next_val = self._next.val
self._next = next(self._generate, None)
return next_val
def hasNext(self) -> bool:
return self._next is not None
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
1139 - 2023-09-24 12:56:22 +0300 MSK
Implement Trie (Prefix Tree)
Links
Code
class Trie:
def __init__(self):
self.root = {}
def insert(self, word: str) -> None:
cur = self.root
for char in word:
if char not in cur:
cur[char] = {}
cur = cur[char]
cur["_is_word"] = None
def search(self, word: str) -> bool:
cur = self.root
for char in word:
if char not in cur:
return False
cur = cur[char]
return "_is_word" in cur
def startsWith(self, prefix: str) -> bool:
cur = self.root
for char in prefix:
if char not in cur:
return False
cur = cur[char]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
1140 - 2023-09-24 12:55:57 +0300 MSK
Combinations
Links
Code
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
current = []
def backtrack(first: int) -> Generator[None, None, List[int]]:
if len(current) == k:
yield tuple(current[:])
return
for i in range(first, n + 1):
current.append(i)
yield from backtrack(i + 1)
current.pop()
return
return tuple(combination for combination in backtrack(1))
1141 - 2023-09-24 12:55:41 +0300 MSK
Permutations
Links
Code
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
length = len(nums)
current = []
current_contains = [False] * length
def backtrack() -> Generator[None, None, List[int]]:
if len(current) == length:
yield tuple(current[:])
return
for i in range(length):
if current_contains[i]:
continue
current_contains[i] = True
current.append(nums[i])
yield from backtrack()
current_contains[i] = False
current.pop()
return
return tuple(combination for combination in backtrack())
1142 - 2023-09-24 12:55:19 +0300 MSK
Generate Parentheses
Links
Code
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
current = []
current_max = n * 2
chars = "()"
def backtrack(open: int, closed: int) -> Generator[None, None, List[str]]:
if len(current) == current_max:
yield "".join(current)
if open:
current.append(chars[0])
yield from backtrack(open - 1, closed)
current.pop()
if closed and closed > open:
current.append(chars[1])
yield from backtrack(open, closed - 1)
current.pop()
return tuple(combination for combination in backtrack(n, n))
1143 - 2023-09-24 12:54:51 +0300 MSK
Maximum Subarray
Links
Code
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
length = len(nums)
if length == 0:
return 0
if length == 1:
return nums[0]
max_cur, max_overall = 0, float("-inf")
for num in nums:
max_cur += num
if max_cur > max_overall:
max_overall = max_cur
if max_cur < 0:
max_cur = 0
return max_overall
1144 - 2023-09-24 12:53:12 +0300 MSK
Median of Two Sorted Arrays
Links
Code
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
m, n = len(nums1), len(nums2)
p1, p2 = 0, 0
# Get the smaller value between nums1[p1] and nums2[p2].
def get_min():
nonlocal p1, p2
if p1 < m and p2 < n:
if nums1[p1] < nums2[p2]:
ans = nums1[p1]
p1 += 1
else:
ans = nums2[p2]
p2 += 1
elif p2 == n:
ans = nums1[p1]
p1 += 1
else:
ans = nums2[p2]
p2 += 1
return ans
if (m + n) % 2 == 0:
for _ in range((m + n) // 2 - 1):
_ = get_min()
return (get_min() + get_min()) / 2
else:
for _ in range((m + n) // 2):
_ = get_min()
return get_min()
1145 - 2023-09-24 12:52:56 +0300 MSK
Search in Rotated Sorted Array
Links
Code
class Solution:
def search(self, nums: List[int], target: int) -> int:
nums_count = len(nums)
left, right = 0, len(nums) - 1
first_num, last_num = nums[0], nums[-1]
if first_num == target:
return 0
if last_num == target:
return nums_count - 1
# Find the index of the pivot element (the smallest element)
while left <= right:
mid = left + (right - left) // 2
if nums[mid] > last_num:
left = mid + 1
else:
right = mid - 1
pivot_num = nums[left]
if pivot_num == target:
return left
if pivot_num < target < last_num:
right = nums_count - 1
else:
left = 0
while left <= right:
mid = left + (right - left) // 2
mid_num = nums[mid]
if mid_num == target:
return mid
elif mid_num > target:
right = mid - 1
else:
left = mid + 1
return -1
1146 - 2023-09-24 12:52:34 +0300 MSK
Single Number II
Links
Code
class Solution:
def singleNumber(self, nums: List[int]) -> int:
nums.sort()
length = len(nums)
for i in range(0, length, 3):
if i == length - 1:
return nums[i]
num_1, num_2, num_3 = nums[i], nums[i+1], nums[i+2]
if num_1 == num_2 == num_3:
continue
if num_2 == num_3:
return num_1
if num_1 == num_3:
return num_2
return num_3
1147 - 2023-09-24 12:52:13 +0300 MSK
Single Number
Links
Code
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(xor, nums)
1148 - 2023-09-24 12:51:48 +0300 MSK
Number of 1 Bits
Links
Code
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n > 0:
if n & 1 != 0:
count += 1
n >>= 1
return count
1149 - 2023-09-24 12:50:52 +0300 MSK
Reverse Bits
Links
Code
class Solution:
def reverseBits(self, n: int) -> int:
# Initialize the reversed number to 0
reversed_num = 0
# Iterate over all 32 bits of the given number
for i in range(32):
# Left shift the reversed number by 1 and add the last bit of the given number to it
reversed_num = (reversed_num << 1) | (n & 1)
# remove the last bit from the original number
n >>= 1
# Return the reversed number
return reversed_num
1150 - 2023-09-24 12:50:33 +0300 MSK
Add Binary
Links
Code
class Solution:
def addBinary(self, a: str, b: str) -> str:
answer = []
carry = 0
for char1, char2 in zip_longest(reversed(a), reversed(b)):
num1, num2 = int(char1) if char1 else 0, int(char2) if char2 else 0
cur_sum = num1 + num2 + carry
carry = 0
if cur_sum > 1:
cur_sum -= 2
carry = 1
answer.append(str(cur_sum))
if carry:
answer.append("1")
return "".join(reversed(answer))
1151 - 2023-09-24 12:47:07 +0300 MSK
Factorial Trailing Zeroes
Links
Code
class Solution:
def trailingZeroes(self, n: int) -> int:
zeros = 0
while n != 0:
new_n = n // 5
zeros += new_n
n = new_n
return zeros
1152 - 2023-09-24 12:44:33 +0300 MSK
Factorial Trailing Zeroes
Links
Code
class Solution:
def trailingZeroes(self, n: int) -> int:
a, b, zeros = 1, 5, 0
while (5**a) <= n:
zeros += n // b
a += 1
b *= 5
return zeros
1153 - 2023-09-24 12:41:55 +0300 MSK
Pow(x, n)
Links
Code
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n < 0:
n *= -1
x = 1 / x
result = 1
while n:
if n % 2:
result *= x
n -= 1
x *= x
n //= 2
return result
1154 - 2023-09-24 12:41:37 +0300 MSK
Plus One
Links
Code
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
carry = 1
for i in reversed(range(len(digits))):
new_digit = digits[i] + carry
if new_digit > 9:
carry = 1
new_digit %= 10
else:
carry = 0
digits[i] = new_digit
if carry:
digits.insert(0, carry)
return digits
1155 - 2023-09-24 12:40:45 +0300 MSK
Partition List
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
before_head, after_head = ListNode(0), ListNode(0)
before_tail, after_tail = before_head, after_head
while head:
if head.val < x:
before_tail.next, before_tail = head, head
else:
after_tail.next, after_tail = head, head
head = head.next
after_tail.next, before_tail.next = None, after_head.next
return before_head.next
1156 - 2023-09-24 12:40:14 +0300 MSK
Reverse Linked List II
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
cur_node = 1
left_head, left_tail = head if left > 1 else None, None
while cur_node < left:
cur_node += 1
head, left_tail = head.next, head
cur_node += 1
mid_head, mid_tail, head = head, head, head.next
mid_head.next = None
while cur_node <= right:
cur_node += 1
mid_head, head.next, head = head, mid_head, head.next
mid_tail.next = head
if left_head:
left_tail.next = mid_head
else:
left_head = mid_head
return left_head
1157 - 2023-09-24 12:39:52 +0300 MSK
Copy List with Random Pointer
Links
Code
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
copied = {None: None}
def copy_node(node: Node) -> Node:
if node in copied:
return copied[node]
new_node = Node(node.val)
copied[node] = new_node
new_node.next = copy_node(node.next)
new_node.random = copy_node(node.random)
return new_node
return copy_node(head)
1158 - 2023-09-24 12:38:31 +0300 MSK
Remove Duplicates from Sorted List II
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
tail, before_tail = head, None
remove_tail = False
while tail:
if tail.next and tail.val == tail.next.val:
tail.next = tail.next.next
remove_tail = True
continue
if not remove_tail:
before_tail, tail = tail, tail.next
continue
remove_tail = False
if before_tail is None:
tail = head.next
head.next, head = None, head.next
else:
before_tail.next = tail.next
tail = tail.next
return head
1159 - 2023-09-24 12:09:18 +0300 MSK
Champagne Tower
Links
Code
class Solution:
def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
if query_row == 0:
return min(1, poured)
if query_glass in (0, query_row):
while query_row and poured:
poured = (poured - 1) / 2 if poured > 1 else 0
query_row -= 1
return min(1, poured)
cur_row, next_row = [0] * (query_row + 2), [0] * (query_row + 2)
cur_row[0] = poured
for row in range(query_row + 1):
next_row[0] = 0
for col in range(row + 1):
overflow = (cur_row[col] - 1) / 2
if overflow > 0:
next_row[col] += overflow
next_row[col + 1] = overflow
else:
next_row[col + 1] = 0
cur_row, next_row = next_row, cur_row
return min(1, next_row[query_glass])
1160 - 2023-09-23 21:54:59 +0300 MSK
Remove Nth Node From End of List
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
cur_length, target_length, before_removed = 0, n + 1, head
tail = head
while tail and cur_length != target_length:
tail = tail.next
cur_length += 1
if not tail and cur_length != target_length:
return head.next
while tail:
before_removed = before_removed.next
tail = tail.next
before_removed.next = before_removed.next.next
return head
1161 - 2023-09-23 18:06:03 +0300 MSK
Rotate List
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if k == 0 or not head:
return head
temp_head, tail, length = head, head, 0
while temp_head:
length += 1
tail, temp_head = temp_head, temp_head.next
rotation = k % length
if rotation == 0:
return head
new_head_idx = length - rotation
new_tail_idx = new_head_idx - 1
i, new_head, new_tail = 0, None, None
temp_head = head
while temp_head:
if i == new_head_idx:
new_head = temp_head
break
if i == new_tail_idx:
new_tail = temp_head
i += 1
temp_head = temp_head.next
tail.next = head
new_tail.next = None
return new_head
1162 - 2023-09-23 13:19:00 +0300 MSK
Longest String Chain
Links
Code
class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=len)
dp = {}
max_chain = 0
for word in words:
dp[word] = 1
for i in range(len(word)):
prev_word = word[:i] + word[i+1:]
if prev_word in dp:
dp[word] = max(dp[word], dp[prev_word] + 1)
max_chain = max(max_chain, dp[word])
return max_chain
1163 - 2023-09-22 18:29:58 +0300 MSK
Minimum Bit Flips to Convert Number
Links
Code
class Solution:
def minBitFlips(self, start: int, goal: int) -> int:
flips_count = 0
while start or goal:
start_is_one, goal_is_one = start & 1, goal & 1
if start_is_one and not goal_is_one or (not start_is_one and goal_is_one):
flips_count += 1
start >>= 1
goal >>= 1
return flips_count
1164 - 2023-09-22 13:51:50 +0300 MSK
Sum of All Subset XOR Totals
Links
Code
class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
return reduce(operator.or_, nums) * 1 << (len(nums) - 1)
1165 - 2023-09-22 13:49:11 +0300 MSK
Sum of All Subset XOR Totals
Links
Code
class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
subsets_count = 2**(len(nums) - 1)
return reduce(operator.or_, nums) * subsets_count
1166 - 2023-09-22 12:14:22 +0300 MSK
Longest Nice Substring
Links
Code
class Solution:
def longestNiceSubstring(self, s: str) -> str:
sSet = set(s)
for i in range(len(s)):
if s[i].lower() not in sSet or s[i].upper() not in sSet:
lns1 = self.longestNiceSubstring(s[:i])
lns2 = self.longestNiceSubstring(s[i+1:])
return max(lns1, lns2, key=len)
return s
1167 - 2023-09-22 11:34:42 +0300 MSK
Count the Number of Consistent Strings
Links
Code
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
allowed = set(allowed)
count = 0
for word in words:
if all(char in allowed for char in word):
count += 1
return count
1168 - 2023-09-22 11:27:41 +0300 MSK
Count the Number of Consistent Strings
Links
Code
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
allowed = set(allowed)
count = 0
for word in words:
if not set(word) - allowed:
count += 1
return count
1169 - 2023-09-22 11:23:55 +0300 MSK
XOR Operation in an Array
Links
Code
class Solution:
def xorOperation(self, n: int, start: int) -> int:
return reduce(lambda total, i: total ^ (start + 2 * i), chain((0, ), range(n)))
1170 - 2023-09-22 10:24:39 +0300 MSK
Binary Gap
Links
Code
class Solution:
def binaryGap(self, n: int) -> int:
i, first_bit = 0, None
max_distance = 0
while n:
is_one = n & 1 == 1
if is_one and first_bit is None:
first_bit = i
elif is_one:
max_distance, first_bit = max(max_distance, i - first_bit), i
n >>= 1
i += 1
return max_distance
1171 - 2023-09-22 08:57:07 +0300 MSK
Is Subsequence
Links
Code
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i = 0
length = len(s)
for char in t:
if i == length:
break
if s[i] == char:
i += 1
return i == length
1172 - 2023-09-22 08:51:25 +0300 MSK
Prime Number of Set Bits in Binary Representation
Links
Code
class Solution:
def countPrimeSetBits(self, left: int, right: int) -> int:
prime_bits = (2, 3, 5, 7, 11, 13, 17, 19)
answer = 0
for num in range(left, right + 1):
bit_count = num.bit_count()
if bit_count in prime_bits:
answer += 1
return answer
1173 - 2023-09-21 19:36:09 +0300 MSK
Set Mismatch
Links
Code
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
length = len(nums)
# dupl_xor_miss = duplicate ^ missing
dupl_xor_miss = reduce(lambda total, i: total ^ i ^ nums[i - 1], range(length + 1))
rightmost_set_bit = dupl_xor_miss & -dupl_xor_miss
xor_group1 = xor_group2 = 0
for i in range(1, length + 1):
if i & rightmost_set_bit:
xor_group1 ^= i
else:
xor_group2 ^= i
if nums[i - 1] & rightmost_set_bit:
xor_group1 ^= nums[i - 1]
else:
xor_group2 ^= nums[i - 1]
for num in nums:
if num == xor_group1:
return num, xor_group2
if num == xor_group2:
return num, xor_group1
raise Exception()
1174 - 2023-09-21 19:11:34 +0300 MSK
Set Mismatch
Links
Code
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
n = len(nums)
dupl_xor_miss = 0
for i in range(1, n+1):
dupl_xor_miss ^= i ^ nums[i-1]
# example for get rightmost set bit
# x: 01110000
# ~x: 10001111
# -x or ~x + 1: 10010000
# x & -x: 00010000
# example for unset rightmost set bit
# x: 01110000
# x-1: 01101111
# x & (x-1): 01100000
rightmost_set_bit = dupl_xor_miss & -dupl_xor_miss
xor_group1 = xor_group2 = 0
for i in range(1, n + 1):
if i & rightmost_set_bit:
xor_group1 ^= i
else:
xor_group2 ^= i
if nums[i-1] & rightmost_set_bit:
xor_group1 ^= nums[i-1]
else:
xor_group2 ^= nums[i-1]
for num in nums:
if num == xor_group1:
return [num, xor_group2]
if num == xor_group2:
return [num, xor_group1]
return []
1175 - 2023-09-21 18:33:03 +0300 MSK
Number Complement
Links
Code
class Solution:
def findComplement(self, num: int) -> int:
return ~num + (1 << num.bit_length())
1176 - 2023-09-21 09:51:52 +0300 MSK
Median of Two Sorted Arrays
Links
Code
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
m, n = len(nums1), len(nums2)
p1, p2 = 0, 0
# Get the smaller value between nums1[p1] and nums2[p2].
def get_min():
nonlocal p1, p2
if p1 < m and p2 < n:
if nums1[p1] < nums2[p2]:
ans = nums1[p1]
p1 += 1
else:
ans = nums2[p2]
p2 += 1
elif p2 == n:
ans = nums1[p1]
p1 += 1
else:
ans = nums2[p2]
p2 += 1
return ans
if (m + n) % 2 == 0:
for _ in range((m + n) // 2 - 1):
_ = get_min()
return (get_min() + get_min()) / 2
else:
for _ in range((m + n) // 2):
_ = get_min()
return get_min()
1177 - 2023-09-20 22:32:26 +0300 MSK
Sum of Values at Indices With K Set Bits
Links
Code
class Solution:
def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
return sum(num for i, num in enumerate(nums) if i.bit_count() == k)
1178 - 2023-09-20 22:28:16 +0300 MSK
Sort Integers by The Number of 1 Bits
Links
Code
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
return tuple(num for num in sorted(arr, key=lambda num: (num.bit_count(), num)))
1179 - 2023-09-20 22:22:48 +0300 MSK
Number of Even and Odd Bits
Links
Code
class Solution:
def evenOddBit(self, n: int) -> List[int]:
return (n & 0x55555555).bit_count(), (n & 0xaaaaaaaa).bit_count()
1180 - 2023-09-20 22:20:17 +0300 MSK
Number of Even and Odd Bits
Links
Code
class Solution:
def evenOddBit(self, n: int) -> List[int]:
even, odd = n & 0x55555555, n & 0xaaaaaaaa
even_count, odd_count = 0, 0
while even:
if even & 1 == 1:
even_count += 1
even >>= 1
while odd:
if odd & 1 == 1:
odd_count += 1
odd >>= 1
return even_count, odd_count
1181 - 2023-09-20 19:50:56 +0300 MSK
Binary Number with Alternating Bits
Links
Code
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
return n & (n >> 1) == 0 and n & (n >> 2) == n >> 2
1182 - 2023-09-20 19:35:10 +0300 MSK
Power of Three
Links
Code
class Solution:
def isPowerOfThree(self, n: int) -> bool:
# 3 ** 20
return n > 0 and 3486784401 % n == 0
1183 - 2023-09-20 19:07:10 +0300 MSK
Power of Two
Links
Code
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (n - 1) == 0
1184 - 2023-09-20 18:36:36 +0300 MSK
Power of Four
Links
Code
class Solution:
def isPowerOfFour(self, n: int) -> bool:
# Check if the number is greater than zero and is a power of two
if n > 0 and (n & (n - 1)) == 0:
# Check if the number is of the form 4^x
return n & 0x55555555 == n
else:
return False
1185 - 2023-09-20 18:32:58 +0300 MSK
Power of Four
Links
Code
class Solution:
def isPowerOfFour(self, n: int) -> bool:
return n and not (n & (n - 1)) and (n & 0x55555555)
1186 - 2023-09-20 18:32:51 +0300 MSK
Power of Four
Links
Code
class Solution:
def isPowerOfFour(self, n: int) -> bool:
return n and not (n & (n - 1)) and (n & 0x55555555)
1187 - 2023-09-20 18:32:34 +0300 MSK
Power of Four
Links
Code
class Solution:
def isPowerOfFour(self, n: int) -> bool:
return n and not (n & (n - 1)) and (n & 0x55555555)
1188 - 2023-09-20 18:02:39 +0300 MSK
Missing Number
Links
Code
class Solution:
def missingNumber(self, nums: List[int]) -> int:
def xor(total: int, i: int) -> int:
return total ^ nums[i] ^ (i + 1)
return reduce(xor, chain((0, ), range(len(nums))))
1189 - 2023-09-20 18:01:50 +0300 MSK
Missing Number
Links
Code
class Solution:
def missingNumber(self, nums: List[int]) -> int:
return reduce(lambda total, i: total ^ nums[i] ^ (i + 1), chain((0, ), range(len(nums))))
1190 - 2023-09-20 17:28:42 +0300 MSK
Missing Number
Links
Code
class Solution:
def missingNumber(self, nums: List[int]) -> int:
length = len(nums)
return ((length + 1) * length) // 2 - sum(nums)
1191 - 2023-09-20 17:07:50 +0300 MSK
Reverse Bits
Links
Code
class Solution:
def reverseBits(self, n: int) -> int:
# Initialize the reversed number to 0
reversed_num = 0
# Iterate over all 32 bits of the given number
for i in range(32):
# Left shift the reversed number by 1 and add the last bit of the given number to it
reversed_num = (reversed_num << 1) | (n & 1)
# remove the last bit from the original number
n >>= 1
# Return the reversed number
return reversed_num
1192 - 2023-09-20 16:31:32 +0300 MSK
Add Binary
Links
Code
class Solution:
def addBinary(self, a: str, b: str) -> str:
answer = []
carry = 0
for char1, char2 in zip_longest(reversed(a), reversed(b)):
num1, num2 = int(char1) if char1 else 0, int(char2) if char2 else 0
cur_sum = num1 + num2 + carry
carry = 0
if cur_sum > 1:
cur_sum -= 2
carry = 1
answer.append(str(cur_sum))
if carry:
answer.append("1")
return "".join(reversed(answer))
1193 - 2023-09-20 11:47:24 +0300 MSK
Minimum Operations to Reduce X to Zero
Links
Code
class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
target, length = sum(nums) - x, len(nums)
max_len = cur_sum = left = 0
if target == 0:
return length
for right, val in enumerate(nums):
cur_sum += val
while left <= right and cur_sum > target:
cur_sum -= nums[left]
left += 1
if cur_sum == target:
max_len = max(max_len, right - left + 1)
return length - max_len if max_len else -1
1194 - 2023-09-19 21:08:16 +0300 MSK
Design Bitset
Links
Code
class Bitset:
def __init__(self, size: int):
self.bits = [0] * size
self.ones_count = 0
self.do_flip = False
self.size = size
def fix(self, idx: int) -> None:
cur = self.bits[idx]
if self.do_flip and cur == 1:
self.ones_count -= 1
self.bits[idx] = 0
elif not self.do_flip and cur == 0:
self.ones_count += 1
self.bits[idx] = 1
def unfix(self, idx: int) -> None:
cur = self.bits[idx]
if self.do_flip and cur == 0:
self.ones_count += 1
self.bits[idx] = 1
elif not self.do_flip and cur == 1:
self.ones_count -= 1
self.bits[idx] = 0
def flip(self) -> None:
self.do_flip = not self.do_flip
def all(self) -> bool:
return self.count() == self.size
def one(self) -> bool:
return self.count() > 0
def count(self) -> int:
return self.size - self.ones_count if self.do_flip else self.ones_count
def toString(self) -> str:
target = (bit ^ 1 for bit in self.bits) if self.do_flip else self.bits
return "".join(str(num) for num in target)
# Your Bitset object will be instantiated and called as such:
# obj = Bitset(size)
# obj.fix(idx)
# obj.unfix(idx)
# obj.flip()
# param_4 = obj.all()
# param_5 = obj.one()
# param_6 = obj.count()
# param_7 = obj.toString()
1195 - 2023-09-19 20:00:19 +0300 MSK
Find the Duplicate Number
Links
Code
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
freqs = [False] * (10**5 + 1)
for num in nums:
if freqs[num] == True:
return num
freqs[num] = True
raise Exception()
1196 - 2023-09-19 19:58:37 +0300 MSK
Find the Duplicate Number
Links
Code
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
freqs = [0] * (10**5 + 1)
for num in nums:
freqs[num] += 1
if freqs[num] > 1:
return num
raise Exception()
1197 - 2023-09-18 15:46:36 +0300 MSK
Product of the Last K Numbers
Links
Code
class ProductOfNumbers:
def __init__(self):
self.products = [1]
def add(self, num: int) -> None:
if num == 0:
self.products.clear()
self.products.append(1)
return
self.products.append(num * self.products[-1])
def getProduct(self, k: int) -> int:
if len(self.products) - 1 < k:
return 0
return self.products[-1] // self.products[-(k + 1)]
# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)
1198 - 2023-09-18 15:46:14 +0300 MSK
Product of the Last K Numbers
Links
Code
class ProductOfNumbers:
def __init__(self):
self.products = [1]
def add(self, num: int) -> None:
if num == 0:
self.products = [1]
return
self.products.append(num * self.products[-1])
def getProduct(self, k: int) -> int:
if len(self.products) - 1 < k:
return 0
return self.products[-1] // self.products[-(k + 1)]
# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)
1199 - 2023-09-18 15:38:04 +0300 MSK
Product of the Last K Numbers
Links
Code
class ProductOfNumbers:
def __init__(self):
self.products, self.last_zero, self.length = [], -1, 0
def add(self, num: int) -> None:
if num == 0:
self.last_zero = self.length
num = 1
self.products.append(num * (self.products[-1] if self.products else 1))
self.length += 1
def getProduct(self, k: int) -> int:
first_elem = self.length - k
if self.last_zero >= first_elem:
return 0
if first_elem == 0:
return self.products[-1]
return self.products[-1] // self.products[first_elem - 1]
# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)
1200 - 2023-09-18 15:35:47 +0300 MSK
Product of the Last K Numbers
Links
Code
class ProductOfNumbers:
def __init__(self):
self.products, self.zero_indexes = [], []
def add(self, num: int) -> None:
if num == 0:
self.zero_indexes.append(len(self.products))
num = 1
new_product = num * (self.products[-1] if self.products else 1)
self.products.append(new_product)
def getProduct(self, k: int) -> int:
first_elem = len(self.products) - k
if self.zero_indexes and self.zero_indexes[-1] >= first_elem:
return 0
if first_elem == 0:
return self.products[-1]
return self.products[-1] // self.products[first_elem - 1]
# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)
1201 - 2023-09-18 15:12:57 +0300 MSK
Find Consecutive Integers from a Data Stream
Links
Code
class DataStream:
def __init__(self, value: int, k: int):
self.required, self.value, self.value_count = k, value, 0
def consec(self, num: int) -> bool:
if num != self.value:
self.value_count = 0
return False
self.value_count += 1
return self.value_count >= self.required
# Your DataStream object will be instantiated and called as such:
# obj = DataStream(value, k)
# param_1 = obj.consec(num)
1202 - 2023-09-18 15:12:07 +0300 MSK
Find Consecutive Integers from a Data Stream
Links
Code
class DataStream:
def __init__(self, value: int, k: int):
self.required, self.value, self.value_count = k, value, 0
def consec(self, num: int) -> bool:
if num != self.value:
self.value_count = 0
return False
self.value_count += 1
return self.value_count >= self.required
# Your DataStream object will be instantiated and called as such:
# obj = DataStream(value, k)
# param_1 = obj.consec(num)
1203 - 2023-09-18 15:00:25 +0300 MSK
Smallest Number in Infinite Set
Links
Code
class SmallestInfiniteSet:
def __init__(self):
self.heap, self.next_num, self.nums = [], 1, set()
def popSmallest(self) -> int:
if self.heap:
val = heappop(self.heap)
self.nums.remove(val)
return val
self.next_num += 1
return self.next_num - 1
def addBack(self, num: int) -> None:
if num in self.nums or num >= self.next_num:
return
self.nums.add(num)
heappush(self.heap, num)
# Your SmallestInfiniteSet object will be instantiated and called as such:
# obj = SmallestInfiniteSet()
# param_1 = obj.popSmallest()
# obj.addBack(num)
1204 - 2023-09-18 14:59:16 +0300 MSK
Smallest Number in Infinite Set
Links
Code
class SmallestInfiniteSet:
def __init__(self):
self.heap, self.next_num, self.nums = [], 1, set()
def popSmallest(self) -> int:
if not self.heap:
self.next_num += 1
return self.next_num - 1
val = heappop(self.heap)
if val < self.next_num:
self.nums.remove(val)
return val
heappush(self.heap, val)
self.next_num += 1
return self.next_num - 1
def addBack(self, num: int) -> None:
if num in self.nums or num >= self.next_num:
return
self.nums.add(num)
heappush(self.heap, num)
# Your SmallestInfiniteSet object will be instantiated and called as such:
# obj = SmallestInfiniteSet()
# param_1 = obj.popSmallest()
# obj.addBack(num)
1205 - 2023-09-18 14:37:29 +0300 MSK
Find Elements in a Contaminated Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class FindElements:
def __init__(self, root: Optional[TreeNode]):
root.val = 0
nodes = [root]
self.values = set((0, ))
while nodes:
node = nodes.pop()
if node.left:
val = 2 * node.val + 1
node.left.val = val
nodes.append(node.left)
self.values.add(val)
if node.right:
val = 2 * node.val + 2
node.right.val = val
nodes.append(node.right)
self.values.add(val)
def find(self, target: int) -> bool:
return target in self.values
# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)
1206 - 2023-09-18 14:34:48 +0300 MSK
Find Elements in a Contaminated Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class FindElements:
def __init__(self, root: Optional[TreeNode]):
self.root = root
root.val = 0
nodes = [root]
while nodes:
node = nodes.pop()
new_val = 2 * node.val
if node.left:
node.left.val = new_val + 1
nodes.append(node.left)
if node.right:
node.right.val = new_val + 2
nodes.append(node.right)
def dfs(self, node: TreeNode, target: int) -> bool:
if not node or node.val > target:
return False
if node.val == target:
return True
return self.dfs(node.left, target) or self.dfs(node.right, target)
def find(self, target: int) -> bool:
return self.dfs(self.root, target)
# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)
1207 - 2023-09-18 13:54:11 +0300 MSK
Range Frequency Queries
Links
Code
class RangeFreqQuery:
def __init__(self, arr: List[int]):
self.l = [[] for _ in range(10001)]
for i, v in enumerate(arr):
self.l[v].append(i)
def query(self, left: int, right: int, v: int) -> int:
return bisect_right(self.l[v], right) - bisect_left(self.l[v], left)
# Your RangeFreqQuery object will be instantiated and called as such:
# obj = RangeFreqQuery(arr)
# param_1 = obj.query(left,right,value)
1208 - 2023-09-18 09:47:53 +0300 MSK
The K Weakest Rows in a Matrix
Links
Code
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
rows_count, cols_count = len(mat), len(mat[0])
heap = []
for i, row in enumerate(mat):
count = 0
for j, val in enumerate(row):
if val == 0:
count = j
break
else:
count = cols_count
heappush(heap, (count, i))
return tuple(item[1] for item in nsmallest(k, heap))
1209 - 2023-09-17 16:27:05 +0300 MSK
Implement Magic Dictionary
Links
Code
class MagicDictionary:
def __init__(self):
self.dict = []
def buildDict(self, dictionary: List[str]) -> None:
self.dict = dictionary
def search(self, searchWord: str) -> bool:
target_length = len(searchWord)
for word in self.dict:
if len(word) != target_length or word == searchWord:
continue
found_diff = False
for i in range(target_length):
if word[i] == searchWord[i]:
continue
if found_diff:
break
found_diff = True
else:
return True
return False
# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dictionary)
# param_2 = obj.search(searchWord)
1210 - 2023-09-17 16:16:53 +0300 MSK
Encode and Decode TinyURL
Links
Code
class Codec:
def __init__(self):
self.urls = []
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
self.urls.append(longUrl)
return len(self.urls)
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return self.urls[shortUrl - 1]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
1211 - 2023-09-17 16:14:59 +0300 MSK
Encode and Decode TinyURL
Links
Code
class Codec:
def __init__(self):
self.urls = {}
self.id = 0
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
id = self.id
self.urls[id] = longUrl
self.id += 1
return id
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return self.urls[int(shortUrl)]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
1212 - 2023-09-17 16:12:53 +0300 MSK
Encode and Decode TinyURL
Links
Code
class Codec:
def __init__(self):
self.urls = []
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
self.urls.append(longUrl)
return str(len(self.urls) - 1)
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return self.urls[int(shortUrl)]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
1213 - 2023-09-17 16:08:12 +0300 MSK
Design Twitter
Links
Code
class Twitter:
def __init__(self):
self.tweets = []
self.following = defaultdict(set)
def postTweet(self, userId: int, tweetId: int) -> None:
self.tweets.append((userId, tweetId))
def getNewsFeed(self, userId: int) -> List[int]:
tweets, following = [], self.following[userId]
for poster, tweet in reversed(self.tweets):
if poster != userId and poster not in following:
continue
tweets.append(tweet)
if len(tweets) == 10:
break
return tweets
def follow(self, followerId: int, followeeId: int) -> None:
self.following[followerId].add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
self.following[followerId].discard(followeeId)
# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)
1214 - 2023-09-17 11:45:39 +0300 MSK
Shortest Path Visiting All Nodes
Links
Code
from collections import deque, namedtuple
class Solution:
def shortestPathLength(self, graph):
n = len(graph)
all_mask = (1 << n) - 1
visited = set()
Node = namedtuple('Node', ['node', 'mask', 'cost'])
q = deque()
for i in range(n):
mask_value = (1 << i)
this_node = Node(i, mask_value, 1)
q.append(this_node)
visited.add((i, mask_value))
while q:
curr = q.popleft()
if curr.mask == all_mask:
return curr.cost - 1
for adj in graph[curr.node]:
both_visited_mask = curr.mask | (1 << adj)
this_node = Node(adj, both_visited_mask, curr.cost + 1)
if (adj, both_visited_mask) not in visited:
visited.add((adj, both_visited_mask))
q.append(this_node)
return -1
1215 - 2023-09-17 11:44:04 +0300 MSK
Implement Trie (Prefix Tree)
Links
Code
class Trie:
def __init__(self):
self.root = {}
def insert(self, word: str) -> None:
cur = self.root
for char in word:
if char not in cur:
cur[char] = {}
cur = cur[char]
cur["_is_word"] = None
def search(self, word: str) -> bool:
cur = self.root
for char in word:
if char not in cur:
return False
cur = cur[char]
return "_is_word" in cur
def startsWith(self, prefix: str) -> bool:
cur = self.root
for char in prefix:
if char not in cur:
return False
cur = cur[char]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
1216 - 2023-09-17 11:40:01 +0300 MSK
Implement Trie (Prefix Tree)
Links
Code
class Node:
def __init__(self):
self.ch, self.is_word = [None] * 128, False
class Trie:
def __init__(self):
self.head = Node()
def insert(self, word: str) -> None:
cur_node = self.head
for i in range(len(word)):
char = ord(word[i])
if cur_node.ch[char] is None:
cur_node.ch[char] = Node()
cur_node = cur_node.ch[char]
cur_node.is_word = True
def search(self, word: str) -> bool:
cur_node = self.head
for i in range(len(word)):
char = ord(word[i])
if cur_node.ch[char] is None:
return False
cur_node = cur_node.ch[char]
return cur_node.is_word
def startsWith(self, prefix: str) -> bool:
cur_node = self.head
for i in range(len(prefix)):
char = ord(prefix[i])
if cur_node.ch[char] is None:
return False
cur_node = cur_node.ch[char]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
1217 - 2023-09-16 21:10:06 +0300 MSK
Apply Discount Every n Orders
Links
Code
class Cashier:
def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
self.freq, self.discount = n, (100 - discount) / 100
self.cur = 0
self.products = {id: price for id, price in zip(products, prices)}
def getBill(self, product: List[int], amount: List[int]) -> float:
self.cur += 1
total = sum(amount[i] * self.products[product[i]] for i in range(len(product)))
if self.cur < self.freq:
return total
self.cur = 0
return total * self.discount
# Your Cashier object will be instantiated and called as such:
# obj = Cashier(n, discount, products, prices)
# param_1 = obj.getBill(product,amount)
1218 - 2023-09-16 21:07:33 +0300 MSK
Apply Discount Every n Orders
Links
Code
class Cashier:
def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
self.freq, self.discount = n, (100 - discount) / 100
self.cur = 0
self.products = {id: price for id, price in zip(products, prices)}
def getBill(self, product: List[int], amount: List[int]) -> float:
self.cur += 1
multiplier = 1
if self.cur == self.freq:
self.cur, multiplier = 0, self.discount
total = sum(amount[i] * self.products[product[i]] for i in range(len(product)))
return total * multiplier
# Your Cashier object will be instantiated and called as such:
# obj = Cashier(n, discount, products, prices)
# param_1 = obj.getBill(product,amount)
1219 - 2023-09-16 20:44:34 +0300 MSK
Design Underground System
Links
Code
class UndergroundSystem:
def __init__(self):
self.from_to = defaultdict(lambda: defaultdict(list))
self.in_transit = {}
def checkIn(self, id: int, stationName: str, t: int) -> None:
self.in_transit[id] = (stationName, t)
def checkOut(self, id: int, stationName: str, t: int) -> None:
station_from, time_from = self.in_transit.pop(id)
self.from_to[station_from][stationName].append(t - time_from)
def getAverageTime(self, startStation: str, endStation: str) -> float:
times = self.from_to[startStation][endStation]
return sum(times) / len(times)
# Your UndergroundSystem object will be instantiated and called as such:
# obj = UndergroundSystem()
# obj.checkIn(id,stationName,t)
# obj.checkOut(id,stationName,t)
# param_3 = obj.getAverageTime(startStation,endStation)
1220 - 2023-09-16 20:20:21 +0300 MSK
Design an Ordered Stream
Links
Code
class OrderedStream:
def __init__(self, n: int):
self.data = [None]*n
self.ptr = 0 # 0-indexed
def insert(self, id: int, value: str) -> List[str]:
id -= 1 # 0-indexed
self.data[id] = value
if id > self.ptr: return [] # not reaching ptr
while self.ptr < len(self.data) and self.data[self.ptr]: self.ptr += 1 # update self.ptr
return self.data[id:self.ptr]
# Your OrderedStream object will be instantiated and called as such:
# obj = OrderedStream(n)
# param_1 = obj.insert(idKey,value)
1221 - 2023-09-16 20:18:19 +0300 MSK
Design an Ordered Stream
Links
Code
class OrderedStream:
def __init__(self, n: int):
self.values = [None] * n
self.length = n
self.cur = 0
def insert(self, idKey: int, value: str) -> List[str]:
self.values[idKey - 1] = value
for i in range(self.cur, self.length):
if self.values[i] is not None:
continue
self.cur, answer = i, self.values[self.cur:i]
return answer
return self.values[self.cur:]
# Your OrderedStream object will be instantiated and called as such:
# obj = OrderedStream(n)
# param_1 = obj.insert(idKey,value)
1222 - 2023-09-16 15:46:43 +0300 MSK
Design Authentication Manager
Links
Code
class AuthenticationManager:
def __init__(self, timeToLive: int):
self.ttl = timeToLive
self.tokens = {}
def generate(self, tokenId: str, currentTime: int) -> None:
self.tokens[tokenId] = currentTime + self.ttl
def renew(self, tokenId: str, currentTime: int) -> None:
if currentTime < self.tokens.get(tokenId, currentTime):
self.generate(tokenId, currentTime)
else:
self.tokens.pop(tokenId, None)
def countUnexpiredTokens(self, currentTime: int) -> int:
count = 0
remove_tokens = []
for token, expir_time in self.tokens.items():
if currentTime < expir_time:
count += 1
else:
remove_tokens.append(token)
for token in remove_tokens:
self.tokens.pop(token)
return count
# Your AuthenticationManager object will be instantiated and called as such:
# obj = AuthenticationManager(timeToLive)
# obj.generate(tokenId,currentTime)
# obj.renew(tokenId,currentTime)
# param_3 = obj.countUnexpiredTokens(currentTime)
1223 - 2023-09-16 15:35:37 +0300 MSK
Seat Reservation Manager
Links
Code
class SeatManager:
def __init__(self, n: int):
self.heap = list(range(1, n + 1))
def reserve(self) -> int:
return heappop(self.heap)
def unreserve(self, seatNumber: int) -> None:
heappush(self.heap, seatNumber)
# Your SeatManager object will be instantiated and called as such:
# obj = SeatManager(n)
# param_1 = obj.reserve()
# obj.unreserve(seatNumber)
1224 - 2023-09-16 15:34:15 +0300 MSK
Seat Reservation Manager
Links
Code
class SeatManager:
def __init__(self, n: int):
self.heap = list(range(1, n + 1))
heapify(self.heap)
def reserve(self) -> int:
return heappop(self.heap)
def unreserve(self, seatNumber: int) -> None:
heappush(self.heap, seatNumber)
# Your SeatManager object will be instantiated and called as such:
# obj = SeatManager(n)
# param_1 = obj.reserve()
# obj.unreserve(seatNumber)
1225 - 2023-09-16 11:35:52 +0300 MSK
Simple Bank System
Links
Code
class Bank:
def __init__(self, balance: List[int]):
self.balance = balance
self.size = len(balance)
def transfer(self, account1: int, account2: int, money: int) -> bool:
if not 0 < account1 <= self.size or not 0 < account2 <= self.size or (
self.balance[account1-1] < money
):
return False
self.balance[account2-1] += money
self.balance[account1-1] -= money
return True
def deposit(self, account: int, money: int) -> bool:
if not 0 < account <= self.size:
return False
self.balance[account-1] += money
return True
def withdraw(self, account: int, money: int) -> bool:
if not 0 < account <= self.size or self.balance[account-1] < money:
return False
self.balance[account-1] -= money
return True
# Your Bank object will be instantiated and called as such:
# obj = Bank(balance)
# param_1 = obj.transfer(account1,account2,money)
# param_2 = obj.deposit(account,money)
# param_3 = obj.withdraw(account,money)
1226 - 2023-09-16 11:25:54 +0300 MSK
Path With Minimum Effort
Links
Code
class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
rows, cols = len(heights), len(heights[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
dist = [[math.inf for _ in range(cols)] for _ in range(rows)]
dist[0][0] = 0
minHeap = [(0, 0, 0)]
while minHeap:
effort, x, y = heappop(minHeap)
if x == rows - 1 and y == cols - 1:
return effort
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < rows and 0 <= ny < cols:
new_effort = max(effort, abs(heights[x][y] - heights[nx][ny]))
if new_effort < dist[nx][ny]:
dist[nx][ny] = new_effort
heappush(minHeap, (new_effort, nx, ny))
1227 - 2023-09-15 19:59:56 +0300 MSK
Design a Number Container System
Links
Code
class NumberContainers:
def __init__(self):
self.num_indices = defaultdict(list)
self.num_at_index = {}
def change(self, index: int, number: int) -> None:
self.num_at_index[index] = number
heapq.heappush(self.num_indices[number], index)
def find(self, number: int) -> int:
while self.num_indices[number] and self.num_at_index[self.num_indices[number][0]] != number:
heapq.heappop(self.num_indices[number])
return self.num_indices[number][0] if len(self.num_indices[number]) > 0 else -1
# Your NumberContainers object will be instantiated and called as such:
# obj = NumberContainers()
# obj.change(index,number)
# param_2 = obj.find(number)
1228 - 2023-09-15 19:53:02 +0300 MSK
Design a Number Container System
Links
Code
import sortedcontainers
class NumberContainers:
def __init__(self):
self._idx_number = {}
self._number_idx = defaultdict(sortedcontainers.SortedSet)
def change(self, index: int, number: int) -> None:
cur_number = self._idx_number.get(index, -1)
if cur_number != -1:
self._number_idx[cur_number].remove(index)
self._idx_number[index] = number
self._number_idx[number].add(index)
def find(self, number: int) -> int:
ids = self._number_idx[number]
return ids[0] if ids else -1
# Your NumberContainers object will be instantiated and called as such:
# obj = NumberContainers()
# obj.change(index,number)
# param_2 = obj.find(number)
1229 - 2023-09-15 19:34:44 +0300 MSK
Finding Pairs With a Certain Sum
Links
Code
class FindSumPairs:
def __init__(self, nums1: List[int], nums2: List[int]):
self._nums1, self._nums2, self._nums2_raw = Counter(nums1), Counter(nums2), nums2
def add(self, index: int, val: int) -> None:
nums2_raw, nums2 = self._nums2_raw, self._nums2
cur_val = nums2_raw[index]
new_val = cur_val + val
if nums2[cur_val] > 0:
nums2[cur_val] -= 1
nums2_raw[index] = new_val
nums2[new_val] += 1
def count(self, tot: int) -> int:
return sum(num1_count * self._nums2.get(tot - num1, 0)
for num1, num1_count in self._nums1.items())
# Your FindSumPairs object will be instantiated and called as such:
# obj = FindSumPairs(nums1, nums2)
# obj.add(index,val)
# param_2 = obj.count(tot)
1230 - 2023-09-15 19:33:23 +0300 MSK
Finding Pairs With a Certain Sum
Links
Code
class FindSumPairs:
def __init__(self, nums1: List[int], nums2: List[int]):
self._nums1, self._nums2, self._nums2_raw = Counter(nums1), Counter(nums2), nums2
def add(self, index: int, val: int) -> None:
nums2_raw, nums2 = self._nums2_raw, self._nums2
cur_val = nums2_raw[index]
new_val = cur_val + val
if nums2[cur_val] > 0:
nums2[cur_val] -= 1
nums2_raw[index] = new_val
nums2[new_val] += 1
def count(self, tot: int) -> int:
sum_count = 0
nums2 = self._nums2
for num1, num1_count in self._nums1.items():
sum_count += num1_count * nums2.get(tot - num1, 0)
return sum_count
# Your FindSumPairs object will be instantiated and called as such:
# obj = FindSumPairs(nums1, nums2)
# obj.add(index,val)
# param_2 = obj.count(tot)
1231 - 2023-09-15 19:12:52 +0300 MSK
Design Browser History
Links
Code
class BrowserHistory:
def __init__(self, homepage: str):
self._history = [homepage]
self._cur = 0
def visit(self, url: str) -> None:
self._history[self._cur+1:] = (url, )
self._cur += 1
def back(self, steps: int) -> str:
self._cur = max(0, self._cur - steps)
return self._history[self._cur]
def forward(self, steps: int) -> str:
self._cur = min(len(self._history) - 1, self._cur + steps)
return self._history[self._cur]
# Your BrowserHistory object will be instantiated and called as such:
# obj = BrowserHistory(homepage)
# obj.visit(url)
# param_2 = obj.back(steps)
# param_3 = obj.forward(steps)
1232 - 2023-09-15 19:05:16 +0300 MSK
Design a Stack With Increment Operation
Links
Code
class CustomStack:
def __init__(self, maxSize: int):
self._stack = []
self._max_size = maxSize
def push(self, x: int) -> None:
if len(self._stack) != self._max_size:
self._stack.append(x)
def pop(self) -> int:
return self._stack.pop() if self._stack else -1
def increment(self, k: int, val: int) -> None:
for i in range(min(k, len(self._stack))):
self._stack[i] += val
# Your CustomStack object will be instantiated and called as such:
# obj = CustomStack(maxSize)
# obj.push(x)
# param_2 = obj.pop()
# obj.increment(k,val)
1233 - 2023-09-15 19:02:42 +0300 MSK
Design a Stack With Increment Operation
Links
Code
class CustomStack:
def __init__(self, maxSize: int):
self._stack = []
self._max_size = maxSize
self._size = 0
def push(self, x: int) -> None:
if self._size == self._max_size:
return
self._stack.append(x)
self._size += 1
def pop(self) -> int:
if self._size == 0:
return -1
last = self._stack.pop()
self._size -= 1
return last
def increment(self, k: int, val: int) -> None:
for i in range(min(k, self._size)):
self._stack[i] += val
# Your CustomStack object will be instantiated and called as such:
# obj = CustomStack(maxSize)
# obj.push(x)
# param_2 = obj.pop()
# obj.increment(k,val)
1234 - 2023-09-15 18:53:00 +0300 MSK
Design Linked List
Links
Code
class Node:
def __init__(self, val: int = 0, prev_node: 'Node' = None, next_node: 'Node' = None):
self.val, self.prev, self.next = val, prev_node, next_node
class MyLinkedList:
def __init__(self):
self._head, self._tail = Node(float("-inf")), Node(float("inf"))
self._head.next, self._tail.prev = self._tail, self._head
self._length = 0
def _getNode(self, index: int) -> Node:
if not 0 <= index < self._length:
return None
if index == 0:
return self._head.next
if index == self._length - 1:
return self._tail.prev
cur_idx, cur_node = 0, self._head.next
while cur_idx < index:
cur_node = cur_node.next
cur_idx += 1
return cur_node
def get(self, index: int) -> int:
node = self._getNode(index)
return node.val if node else -1
def addAtHead(self, val: int) -> None:
old_first = self._head.next
new_node = Node(val, self._head, old_first)
self._head.next, old_first.prev = new_node, new_node
self._length += 1
def addAtTail(self, val: int) -> None:
old_tail = self._tail.prev
new_node = Node(val, old_tail, self._tail)
self._tail.prev, old_tail.next = new_node, new_node
self._length += 1
def addAtIndex(self, index: int, val: int) -> None:
if not 0 <= index <= self._length:
return
if index == 0:
self.addAtHead(val)
return
if index == self._length:
self.addAtTail(val)
return
target_node = self._getNode(index)
prev_node = target_node.prev
new_node = Node(val, prev_node, target_node)
prev_node.next, target_node.prev = new_node, new_node
self._length += 1
def deleteAtIndex(self, index: int) -> None:
if not 0 <= index < self._length:
return
target_node = self._getNode(index)
old_prev, old_next = target_node.prev, target_node.next
old_prev.next, old_next.prev = old_next, old_prev
self._length -= 1
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
1235 - 2023-09-15 17:07:59 +0300 MSK
Range Sum Query 2D - Immutable
Links
Code
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
self.dp=[[0] * (len(matrix[0])+1) for _ in range(len(matrix)+1)]
# calculate prefix sum
for r in range(len(self.dp)-1):
for c in range(len(self.dp[0])-1):
self.dp[r+1][c+1]=matrix[r][c] + self.dp[r][c+1] + self.dp[r+1][c] - self.dp[r][c]
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
return self.dp[row2+1][col2+1] - self.dp[row1][col2+1] - self.dp[row2+1][col1] + self.dp[row1][col1]
1236 - 2023-09-15 12:51:11 +0300 MSK
Peeking Iterator
Links
Code
# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator:
# def __init__(self, nums):
# """
# Initializes an iterator object to the beginning of a list.
# :type nums: List[int]
# """
#
# def hasNext(self):
# """
# Returns true if the iteration has more elements.
# :rtype: bool
# """
#
# def next(self):
# """
# Returns the next element in the iteration.
# :rtype: int
# """
class PeekingIterator:
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self._iter = iterator
self._next = iterator.next()
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self._next
def next(self):
"""
:rtype: int
"""
cur_next = self._next
self._next = self._iter.next() if self._iter.hasNext() else None
return cur_next
def hasNext(self):
"""
:rtype: bool
"""
return self._next is not None
# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
# val = iter.peek() # Get the next element but not advance the iterator.
# iter.next() # Should return the same value as [val].
1237 - 2023-09-15 09:59:15 +0300 MSK
Min Cost to Connect All Points
Links
Code
def manhattan_distance(p1: List[int], p2: List[int]) -> int:
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
n = len(points)
visited = [False] * n
heap_dict = {0: 0}
min_heap = [(0, 0)]
mst_weight = 0
while min_heap:
w, u = heappop(min_heap)
if visited[u] or heap_dict.get(u, float('inf')) < w:
continue
visited[u] = True
mst_weight += w
for v in range(n):
if not visited[v]:
new_distance = manhattan_distance(points[u], points[v])
if new_distance < heap_dict.get(v, float('inf')):
heap_dict[v] = new_distance
heappush(min_heap, (new_distance, v))
return mst_weight
1238 - 2023-09-14 19:02:15 +0300 MSK
Frequency Tracker
Links
Code
class FrequencyTracker:
def __init__(self):
self._num_freq = defaultdict(int)
self._freq_nums = defaultdict(set)
def add(self, number: int) -> None:
cur_freq = self._num_freq[number]
self._num_freq[number] = cur_freq + 1
self._freq_nums[cur_freq].discard(number)
self._freq_nums[cur_freq + 1].add(number)
def deleteOne(self, number: int) -> None:
cur_freq = self._num_freq[number]
if cur_freq == 0:
return
self._num_freq[number] = cur_freq - 1
self._freq_nums[cur_freq].discard(number)
if cur_freq != 1:
self._freq_nums[cur_freq - 1].add(number)
def hasFrequency(self, frequency: int) -> bool:
return len(self._freq_nums[frequency]) != 0
# Your FrequencyTracker object will be instantiated and called as such:
# obj = FrequencyTracker()
# obj.add(number)
# obj.deleteOne(number)
# param_3 = obj.hasFrequency(frequency)
1239 - 2023-09-14 18:45:02 +0300 MSK
Design an ATM Machine
Links
Code
class ATM:
def __init__(self):
self._banknotes = (0, ) * 5
self._values = (20, 50, 100, 200, 500)
def deposit(self, banknotesCount: List[int]) -> None:
self._banknotes = tuple(banknotesCount[i] + self._banknotes[i] for i in range(5))
def withdraw(self, amount: int) -> List[int]:
withdrawn = [0] * 5
for i in reversed(range(5)):
value, notes_left = self._values[i], self._banknotes[i]
notes_need = min(notes_left, amount // value)
if notes_need == 0:
continue
amount -= value * notes_need
withdrawn[i] = notes_need
if amount == 0:
self._banknotes = tuple(self._banknotes[i] - withdrawn[i]
for i in range(5))
return withdrawn
return (-1, )
# Your ATM object will be instantiated and called as such:
# obj = ATM()
# obj.deposit(banknotesCount)
# param_2 = obj.withdraw(amount)
1240 - 2023-09-14 18:44:27 +0300 MSK
Design an ATM Machine
Links
Code
class ATM:
def __init__(self):
self._banknotes = (0, ) * 5
self._values = (20, 50, 100, 200, 500)
def deposit(self, banknotesCount: List[int]) -> None:
self._banknotes = tuple(banknotesCount[i] + self._banknotes[i] for i in range(5))
def withdraw(self, amount: int) -> List[int]:
withdrawn = [0] * 5
for i in reversed(range(5)):
value, notes_left = self._values[i], self._banknotes[i]
notes_need = min(notes_left, amount // value)
if notes_need == 0:
continue
amount -= value * notes_need
withdrawn[i] = notes_need
if amount == 0:
self._banknotes = tuple(self._banknotes[i] - withdrawn[i]
for i in range(5))
return withdrawn
return (-1, )
# Your ATM object will be instantiated and called as such:
# obj = ATM()
# obj.deposit(banknotesCount)
# param_2 = obj.withdraw(amount)
1241 - 2023-09-14 18:40:55 +0300 MSK
Design an ATM Machine
Links
Code
class ATM:
def __init__(self):
self._banknotes = [0] * 5
self._values = (20, 50, 100, 200, 500)
def deposit(self, banknotesCount: List[int]) -> None:
for i in range(5):
self._banknotes[i] += banknotesCount[i]
def withdraw(self, amount: int) -> List[int]:
withdrawn = [0] * 5
for i in reversed(range(5)):
value, notes_left = self._values[i], self._banknotes[i]
notes_need = min(notes_left, amount // value)
if notes_need == 0:
continue
amount -= value * notes_need
withdrawn[i] = notes_need
if amount == 0:
for i in range(5):
self._banknotes[i] -= withdrawn[i]
return withdrawn
return [-1]
# Your ATM object will be instantiated and called as such:
# obj = ATM()
# obj.deposit(banknotesCount)
# param_2 = obj.withdraw(amount)
1242 - 2023-09-14 18:08:10 +0300 MSK
Design Memory Allocator
Links
Code
class Allocator:
def __init__(self, n: int):
self._units = [1] * n
self._units[0] = n
self._id_units = defaultdict(list)
self._units_count = n
def find_avail_units(self, start: int, size: int) -> Tuple[int, int]:
i = start
count = 0
while i < self._units_count and i - start < size:
units_avail = self._units[i]
if units_avail < 0:
return i + units_avail if i == start else i, count
i += units_avail
count += units_avail
return i, count
def allocate(self, size: int, mID: int) -> int:
i = 0
units_start, units_count = None, 0
while i < self._units_count and units_count < size:
units_avail = self._units[i]
if units_avail < 0:
i += -units_avail
units_start, units_count = None, 0
continue
if units_start is None:
units_start = i
units_count += units_avail
i += units_avail
if units_count < size:
return -1
self._units[units_start] = -size
if units_count > size:
self._units[units_start + size] = units_count - size
self._id_units[mID].append(units_start)
return units_start
def free(self, mID: int) -> int:
count = 0
conseq_units = self._id_units[mID]
while conseq_units:
units_start = conseq_units.pop()
units_freed = -self._units[units_start]
count += units_freed
self._units[units_start] = units_freed
return count
# Your Allocator object will be instantiated and called as such:
# obj = Allocator(n)
# param_1 = obj.allocate(size,mID)
# param_2 = obj.free(mID)
1243 - 2023-09-14 14:41:43 +0300 MSK
Reconstruct Itinerary
Links
Code
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
graph = defaultdict(list)
for src, dst in sorted(tickets, reverse=True):
graph[src].append(dst)
itinerary = []
def dfs(airport: str) -> None:
while graph[airport]:
dfs(graph[airport].pop())
itinerary.append(airport)
dfs("JFK")
return itinerary[::-1]
1244 - 2023-09-13 19:20:05 +0300 MSK
Detect Squares
Links
Code
class DetectSquares:
def __init__(self):
self._row_col = defaultdict(lambda: defaultdict(int))
def add(self, point: List[int]) -> None:
self._row_col[point[0]][point[1]] += 1
def count(self, point: List[int]) -> int:
ways_count = 0
row1, col1 = point
for col2, col2_count in self._row_col[row1].items():
if col2 == col1:
continue
side = col2 - col1
for row2 in (row1 + side, row1 - side):
point3_count = self._row_col[row2][col1]
point4_count = self._row_col[row2][col2]
ways_count += col2_count * point3_count * point4_count
return ways_count
# Your DetectSquares object will be instantiated and called as such:
# obj = DetectSquares()
# obj.add(point)
# param_2 = obj.count(point)
1245 - 2023-09-13 11:18:48 +0300 MSK
Candy
Links
Code
class Solution:
def candy(self, ratings: List[int]) -> int:
child_count = len(ratings)
candies = [1] * child_count
for i in range(1, child_count):
if ratings[i] > ratings[i-1]:
candies[i] = candies[i-1] + 1
for i in reversed(range(child_count - 1)):
if ratings[i] > ratings[i+1]:
candies[i] = max(candies[i], candies[i+1] + 1)
return sum(candies)
1246 - 2023-09-12 19:36:36 +0300 MSK
Tweet Counts Per Frequency
Links
Code
class TweetCounts:
def __init__(self):
self._tweets = defaultdict(list)
self._chunk_ranges = {
"minute": 60,
"hour": 3600,
"day": 86400
}
def recordTweet(self, tweetName: str, time: int) -> None:
self._tweets[tweetName].append(time)
def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:
chunk_range = self._chunk_ranges[freq]
chunks = [0] * (1 + (endTime - startTime) // chunk_range)
for tweet in self._tweets[tweetName]:
if not startTime <= tweet <= endTime:
continue
chunks[(tweet - startTime) // chunk_range] += 1
return chunks
# Your TweetCounts object will be instantiated and called as such:
# obj = TweetCounts()
# obj.recordTweet(tweetName,time)
# param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime)
1247 - 2023-09-12 16:32:10 +0300 MSK
Snapshot Array
Links
Code
class SnapshotArray:
def __init__(self, length: int):
self._cur_snap = 0
self._elems = [[(0, 0)] for _ in range(length)]
def set(self, index: int, val: int) -> None:
values = self._elems[index]
if values[-1][0] == self._cur_snap:
values.pop()
values.append((self._cur_snap, val))
def snap(self) -> int:
self._cur_snap += 1
return self._cur_snap - 1
def get(self, index: int, snap_id: int) -> int:
for cur_snap_id, val in reversed(self._elems[index]):
if cur_snap_id > snap_id:
continue
return val
return -1
# Your SnapshotArray object will be instantiated and called as such:
# obj = SnapshotArray(length)
# obj.set(index,val)
# param_2 = obj.snap()
# param_3 = obj.get(index,snap_id)
1248 - 2023-09-12 15:42:35 +0300 MSK
Time Based Key-Value Store
Links
Code
class TimeMap:
def __init__(self):
self._cache = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self._cache[key].append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
for cur_timestamp, value in reversed(self._cache[key]):
if cur_timestamp > timestamp:
continue
return value
return ""
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)
1249 - 2023-09-12 15:27:56 +0300 MSK
Design Parking System
Links
Code
class ParkingSystem:
def __init__(self, big: int, medium: int, small: int):
self._slots = [0, big, medium, small]
def addCar(self, carType: int) -> bool:
slots_avail = self._slots[carType]
if not slots_avail:
return False
self._slots[carType] = slots_avail - 1
return True
# Your ParkingSystem object will be instantiated and called as such:
# obj = ParkingSystem(big, medium, small)
# param_1 = obj.addCar(carType)
1250 - 2023-09-12 15:23:56 +0300 MSK
Design Parking System
Links
Code
class ParkingSystem:
def __init__(self, big: int, medium: int, small: int):
self._slots = [big, medium, small]
def addCar(self, carType: int) -> bool:
if self._slots[carType-1] == 0:
return False
self._slots[carType-1] -= 1
return True
# Your ParkingSystem object will be instantiated and called as such:
# obj = ParkingSystem(big, medium, small)
# param_1 = obj.addCar(carType)
1251 - 2023-09-12 15:21:06 +0300 MSK
Number of Recent Calls
Links
Code
class RecentCounter:
def __init__(self):
self._queue = deque()
def ping(self, t: int) -> int:
self._queue.append(t)
while self._queue:
if t - self._queue[0] > 3000:
self._queue.popleft()
else:
break
return len(self._queue)
# Your RecentCounter object will be instantiated and called as such:
# obj = RecentCounter()
# param_1 = obj.ping(t)
1252 - 2023-09-12 14:23:58 +0300 MSK
Range Sum Query - Immutable
Links
Code
class NumArray:
def __init__(self, nums: List[int]):
self._sums = tuple(accumulate(nums))
def sumRange(self, left: int, right: int) -> int:
# [-2, 0, 3, -5, 2, -1], [-2, -2, 1, -4, -2, -3]
# [0, 2] -> 1
if left == 0:
return self._sums[right]
return self._sums[right] - self._sums[left-1]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)
1253 - 2023-09-12 14:12:53 +0300 MSK
Range Sum Query - Immutable
Links
Code
class NumArray:
def __init__(self, nums: List[int]):
self._nums = nums
@cache
def sumRange(self, left: int, right: int) -> int:
if right == left:
return self._nums[left]
if right - left == 1:
return self._nums[right] + self._nums[left]
mid = left + (right - left) // 2
return self.sumRange(left, mid) + self.sumRange(mid + 1, right)
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)
1254 - 2023-09-12 14:07:17 +0300 MSK
Range Sum Query - Immutable
Links
Code
class NumArray:
def __init__(self, nums: List[int]):
self._nums = nums
def sumRange(self, left: int, right: int) -> int:
return sum(self._nums[left:right+1])
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)
1255 - 2023-09-12 14:05:44 +0300 MSK
Binary Search Tree Iterator
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
def generate(node: TreeNode) -> int:
if not node:
return
yield from generate(node.left)
yield node
yield from generate(node.right)
self._generate = generate(root)
self._next = next(self._generate)
def next(self) -> int:
next_val = self._next.val
self._next = next(self._generate, None)
return next_val
def hasNext(self) -> bool:
return self._next is not None
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
1256 - 2023-09-12 14:05:12 +0300 MSK
Binary Search Tree Iterator
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
def generate(node: TreeNode) -> int:
if not node:
return
yield from generate(node.left)
yield node
yield from generate(node.right)
self._generate = generate(root)
self._next = next(self._generate)
def next(self) -> int:
next_val = self._next.val
self._next = next(self._generate, None)
return next_val
def hasNext(self) -> bool:
return not self._next is None
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
1257 - 2023-09-12 14:01:45 +0300 MSK
Binary Search Tree Iterator
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self._stack = []
while root:
self._stack.append(root)
root = root.left
def next(self) -> int:
node = self._stack.pop()
right = node.right
while right:
self._stack.append(right)
right = right.left
return node.val
def hasNext(self) -> bool:
return self._stack
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
1258 - 2023-09-12 11:17:46 +0300 MSK
Balanced Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def get_height(node: TreeNode) -> int:
if not node:
return 0
h_left = get_height(node.left)
if h_left < 0:
return -1
h_right = get_height(node.right)
if h_right < 0 or abs(h_left - h_right) > 1:
return -1
return max(h_left, h_right) + 1
return get_height(root) >= 0
1259 - 2023-09-12 10:55:04 +0300 MSK
Minimum Deletions to Make Character Frequencies Unique
Links
Code
class Solution:
def minDeletions(self, s: str) -> int:
length = len(s)
char_count = Counter(s)
counts = set()
deleted_chars = 0
for char, count in char_count.items():
while count != 0 and count in counts:
count -= 1
deleted_chars += 1
if count != 0:
counts.add(count)
return deleted_chars
1260 - 2023-09-11 19:32:16 +0300 MSK
Intersection of Two Linked Lists
Links
Code
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
if not headA or not headB:
return None
tail1, tail2 = headA, headB
while tail1 != tail2:
tail1 = tail1.next if tail1 else headB
tail2 = tail2.next if tail2 else headA
return tail2
1261 - 2023-09-11 19:31:11 +0300 MSK
Intersection of Two Linked Lists
Links
Code
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
if headA and headB:
A, B = headA, headB
while A != B:
A = A.next if A else headB
B = B.next if B else headA
return B
1262 - 2023-09-11 19:16:39 +0300 MSK
Pascal’s Triangle II
Links
Code
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
prev_row = (1,)
for i in range(1, rowIndex + 1):
prev_row = (1, *(prev_row[j] + prev_row[j+1] for j in range(len(prev_row) - 1)), 1)
return prev_row
1263 - 2023-09-11 19:06:00 +0300 MSK
Single Number
Links
Code
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(xor, nums)
1264 - 2023-09-11 18:58:15 +0300 MSK
Single Number
Links
Code
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(lambda total, element: total ^ element, nums)
1265 - 2023-09-11 18:55:49 +0300 MSK
Single Number
Links
Code
class Solution:
def singleNumber(self, nums: List[int]) -> int:
nums_count = len(nums)
if nums_count == 1:
return nums[0]
nums.sort()
for i in range(0, nums_count, 2):
if i + 1 == nums_count:
return nums[i]
cur_num, next_num = nums[i], nums[i+1]
if cur_num == next_num:
continue
return cur_num
return 0
1266 - 2023-09-11 18:46:11 +0300 MSK
Minimum Depth of Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
def dfs(node: TreeNode) -> int:
if not node:
return 0
return 1 + min((depth for depth in (dfs(node.left), dfs(node.right)) if depth > 0),
default=0)
return dfs(root)
1267 - 2023-09-11 18:31:16 +0300 MSK
Binary Tree Inorder Traversal
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
def get_nodes(root: TreeNode) -> Generator[None, None, TreeNode]:
if not root:
return
yield from get_nodes(root.left)
yield root.val
yield from get_nodes(root.right)
return tuple(get_nodes(root))
1268 - 2023-09-11 18:30:56 +0300 MSK
Binary Tree Inorder Traversal
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
def get_nodes(root: TreeNode) -> Generator[None, None, TreeNode]:
if not root:
return
if root.left:
yield from get_nodes(root.left)
yield root.val
if root.right:
yield from get_nodes(root.right)
return tuple(get_nodes(root))
1269 - 2023-09-11 15:06:55 +0300 MSK
Group the People Given the Group Size They Belong To
Links
Code
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
answer = []
cur_groups = defaultdict(list)
for i in range(len(groupSizes)):
size = groupSizes[i]
group = cur_groups[size]
group.append(i)
if len(group) == size:
answer.append(group)
del cur_groups[size]
return answer
1270 - 2023-09-10 12:48:15 +0300 MSK
Count All Valid Pickup and Delivery Options
Links
Code
class Solution:
def countOrders(self, n: int) -> int:
# P1, D1 [01] -> (P1, D1)
# P1, D1, P2, D2 [06] -> (P1, P2, D1, D2), (P1, P2, D2, D1),
# (P1, D1, P2, D2), (P2, P1, D1, D2),
# (P2, P1, D2, D1), (P2, D2, P1, D1).
# P1, D1, P2, D2, P3, D3 [90]
ways_count = 1
mod = 10**9 + 7
for order in range(2, n + 1):
pos_avail_count = 1 + (order - 1) * 2
cur_ways_count = pos_avail_count * (pos_avail_count + 1) // 2
ways_count = (ways_count * cur_ways_count) % mod
return ways_count
1271 - 2023-09-10 12:37:39 +0300 MSK
Count All Valid Pickup and Delivery Options
Links
Code
class Solution:
def countOrders(self, n: int) -> int:
# P1, D1 [01] -> (P1, D1)
# P1, D1, P2, D2 [06] -> (P1, P2, D1, D2), (P1, P2, D2, D1),
# (P1, D1, P2, D2), (P2, P1, D1, D2),
# (P2, P1, D2, D1), (P2, D2, P1, D1).
# P1, D1, P2, D2, P3, D3 [90]
ways_count = 1
for order in range(2, n + 1):
avail_pos_count = 1 + (order - 1) * 2
ways_count *= sum(avail_pos_count - pos for pos in range(avail_pos_count))
return ways_count % (10**9 + 7)
1272 - 2023-09-09 20:12:03 +0300 MSK
Decode Ways
Links
Code
class Solution:
def numDecodings(self, s: str) -> int:
char_count = len(s)
@cache
def dfs(i: int) -> int:
if i == char_count:
return 1
if s[i] == "0":
return 0
return dfs(i + 1) + (
dfs(i + 2) if i + 1 < char_count and s[i:i+2] < "27" else 0
)
return dfs(0)
1273 - 2023-09-09 20:11:23 +0300 MSK
Decode Ways
Links
Code
class Solution:
def numDecodings(self, s: str) -> int:
char_count = len(s)
@cache
def dfs(i: int) -> int:
if i == char_count:
return 1
if s[i] == "0":
return 0
return dfs(i + 1) + (dfs(i + 2) if i + 1 < char_count and s[i:i+2] < "27" else 0)
return dfs(0)
1274 - 2023-09-09 20:10:19 +0300 MSK
Decode Ways
Links
Code
class Solution:
def numDecodings(self, s: str) -> int:
char_count = len(s)
@cache
def dfs(i: int) -> int:
if i == char_count:
return 1
if s[i] == "0":
return 0
ways_count = dfs(i + 1)
if i + 1 < char_count and s[i:i+2] < "27":
ways_count += dfs(i + 2)
return ways_count
return dfs(0)
1275 - 2023-09-09 16:06:56 +0300 MSK
Snakes and Ladders
Links
Code
class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
n = len(board)
board.reverse()
def intToPos(square):
r = (square - 1) // n
c = (square - 1) % n
if r % 2:
c = n - 1 - c
return [r, c]
q = deque()
q.append([1, 0])
visit = set()
while q:
square, moves = q.popleft()
for i in range(1, 7):
nextSquare = square + i
r, c = intToPos(nextSquare)
if board[r][c] != -1:
nextSquare = board[r][c]
if nextSquare == n * n:
return moves + 1
if nextSquare not in visit:
visit.add(nextSquare)
q.append([nextSquare, moves + 1])
return -1
1276 - 2023-09-09 10:20:58 +0300 MSK
Combination Sum IV
Links
Code
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
@cache
def dp(cur_sum: int) -> int:
if cur_sum == target:
return 1
if cur_sum > target:
return 0
return sum(dp(cur_sum + num) for num in nums)
return dp(0)
1277 - 2023-09-09 10:20:26 +0300 MSK
Combination Sum IV
Links
Code
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
@cache
def backtrack(cur_sum: int) -> int:
if cur_sum == target:
return 1
if cur_sum > target:
return 0
return sum(backtrack(cur_sum + num) for num in nums)
return backtrack(0)
1278 - 2023-09-08 13:41:10 +0300 MSK
Pascal’s Triangle
Links
Code
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
answer = [[1]]
numRows -= 1
while numRows > 0:
cur, prev = [1], answer[-1]
for i in range(len(prev) - 1):
cur.append(prev[i] + prev[i+1])
cur.append(1)
answer.append(cur)
numRows -= 1
return answer
1279 - 2023-09-07 20:09:04 +0300 MSK
Word Search
Links
Code
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
row_count, col_count = len(board), len(board[0])
word_length = len(word)
delta = ((0, 1), (0, -1), (1, 0), (-1, 0))
if word_length == 1:
return any(word in row for row in board)
if word_length > row_count * col_count:
return False
visited = set()
def backtrack(row: int, col: int, target: int) -> bool:
if target == word_length:
return True
if not 0 <= row < row_count or not 0 <= col < col_count or (
(row, col) in visited or board[row][col] != word[target]
):
return False
visited.add((row, col))
answer = any(backtrack(row + delta_row, col + delta_col, target + 1)
for delta_row, delta_col in delta)
visited.remove((row, col))
return answer
return any(backtrack(row, col, 0)
for row in range(row_count)
for col in range(col_count))
1280 - 2023-09-07 20:00:09 +0300 MSK
Word Search
Links
Code
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
row_count, col_count = len(board), len(board[0])
word_length = len(word)
delta = ((0, 1), (0, -1), (1, 0), (-1, 0))
if word_length == 1:
return any(word in row for row in board)
def backtrack(row: int, col: int, visited: Set, target: int) -> bool:
if (row, col) in visited or not 0 <= row < row_count or not 0 <= col < col_count:
return False
if board[row][col] != word[target]:
return False
if target == word_length - 1:
return True
visited.add((row, col))
if any(backtrack(row + delta_row, col + delta_col, visited, target + 1)
for delta_row, delta_col in delta):
return True
visited.remove((row, col))
return False
start_char = word[0]
return any(backtrack(row, col, set(), 0)
for row in range(row_count)
for col in range(col_count)
if board[row][col] == start_char)
1281 - 2023-09-07 19:55:32 +0300 MSK
Word Search
Links
Code
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
row_count, col_count = len(board), len(board[0])
word_length = len(word)
delta = ((0, 1), (0, -1), (1, 0), (-1, 0))
if word_length == 1:
return any(word in row for row in board)
def backtrack(row: int, col: int, visited: Set, target: int) -> bool:
if (row, col) in visited or not 0 <= row < row_count or not 0 <= col < col_count:
return False
if board[row][col] != word[target]:
return False
if target == word_length - 1:
return True
visited.add((row, col))
if any(backtrack(row + delta_row, col + delta_col, visited, target + 1)
for delta_row, delta_col in delta):
return True
visited.remove((row, col))
return False
for row in range(row_count):
for col in range(col_count):
if backtrack(row, col, set(), 0):
return True
return False
1282 - 2023-09-07 17:13:51 +0300 MSK
Reverse Linked List II
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
cur_node = 1
left_head, left_tail = head if left > 1 else None, None
while cur_node < left:
cur_node += 1
head, left_tail = head.next, head
cur_node += 1
mid_head, mid_tail, head = head, head, head.next
mid_head.next = None
while cur_node <= right:
cur_node += 1
mid_head, head.next, head = head, mid_head, head.next
mid_tail.next = head
if left_head:
left_tail.next = mid_head
else:
left_head = mid_head
return left_head
1283 - 2023-09-07 17:13:34 +0300 MSK
Reverse Linked List II
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
cur_node = 1
left_head, left_tail = head if left > 1 else None, None
while cur_node < left:
cur_node += 1
head, left_tail = head.next, head
cur_node += 1
mid_head, mid_tail, head = head, head, head.next
mid_head.next = None
while cur_node <= right:
cur_node += 1
next_node = head.next
mid_head, head.next = head, mid_head
head = next_node
mid_tail.next = head
if left_head:
left_tail.next = mid_head
else:
left_head = mid_head
return left_head
1284 - 2023-09-07 17:12:50 +0300 MSK
Reverse Linked List II
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
cur_node = 1
left_head, left_tail = head if left > 1 else None, None
while cur_node < left:
cur_node += 1
head, left_tail = head.next, head
cur_node += 1
mid_head, mid_tail, head = head, head, head.next
mid_head.next = None
while cur_node <= right:
cur_node += 1
next_node = head.next
head.next = mid_head
mid_head = head
head = next_node
mid_tail.next = head
if left_head:
left_tail.next = mid_head
else:
left_head = mid_head
return left_head
1285 - 2023-09-06 14:59:03 +0300 MSK
Split Linked List in Parts
Links
Code
class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
nodes_count = 0
tail = head
while tail:
tail = tail.next
nodes_count += 1
quotient, remainder = divmod(nodes_count, k)
answer = []
for i in range(k):
size = quotient + 1 if (remainder := remainder - 1) >= 0 else quotient
answer.append(head)
last = None
while size > 0:
last = head
head = head.next
size -= 1
if last:
last.next = None
return answer
1286 - 2023-09-05 11:41:23 +0300 MSK
Copy List with Random Pointer
Links
Code
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
copied = {None: None}
def copy_node(node: Node) -> Node:
if node in copied:
return copied[node]
new_node = Node(node.val)
copied[node] = new_node
new_node.next = copy_node(node.next)
new_node.random = copy_node(node.random)
return new_node
return copy_node(head)
1287 - 2023-09-04 15:54:45 +0300 MSK
Combination Sum
Links
Code
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = set()
cur_nums = []
def backtrack(cur_sum: int) -> None:
if cur_sum == target:
result.add(tuple(sorted(cur_nums[:])))
if cur_sum >= target:
return
for num in candidates:
cur_nums.append(num)
backtrack(num + cur_sum)
cur_nums.pop()
backtrack(0)
return result
1288 - 2023-09-04 12:44:01 +0300 MSK
Convert Sorted Array to Binary Search Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
nums_count = len(nums)
if nums_count == 0:
return None
mid = nums_count // 2
return TreeNode(nums[mid],
self.sortedArrayToBST(nums[:mid]),
self.sortedArrayToBST(nums[mid+1:]))
1289 - 2023-09-04 09:37:09 +0300 MSK
Linked List Cycle
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow_p, fast_p = head, head.next if head else None
while fast_p and fast_p.next:
if slow_p == fast_p:
return True
slow_p, fast_p = slow_p.next, fast_p.next.next
return False
1290 - 2023-09-03 20:06:29 +0300 MSK
Game of Life
Links
Code
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
rows_count, cols_count = len(board), len(board[0])
moves = ((0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1))
flip_cells = set()
for row in range(rows_count):
for col in range(cols_count):
live_neighbors = 0
is_alive = board[row][col] == 1
for row_delta, col_delta in moves:
new_row, new_col = row + row_delta, col + col_delta
if not 0 <= new_row < rows_count or not 0 <= new_col < cols_count:
continue
if board[new_row][new_col] == 1:
live_neighbors += 1
if (is_alive and (live_neighbors < 2 or live_neighbors > 3)) or (
not is_alive and live_neighbors == 3
):
flip_cells.add((row, col))
while flip_cells:
row, col = flip_cells.pop()
board[row][col] = 0 if board[row][col] == 1 else 1
1291 - 2023-09-03 19:49:38 +0300 MSK
Set Matrix Zeroes
Links
Code
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
rows_count, cols_count = len(matrix), len(matrix[0])
flip_rows, flip_cols = set(), set()
for row in range(rows_count):
for col in range(cols_count):
if matrix[row][col] == 0:
flip_rows.add(row)
flip_cols.add(col)
while flip_rows:
row = flip_rows.pop()
for col in range(cols_count):
if matrix[row][col] != 0:
matrix[row][col] = 0
while flip_cols:
col = flip_cols.pop()
for row in range(rows_count):
if matrix[row][col] != 0:
matrix[row][col] = 0
1292 - 2023-09-03 11:23:58 +0300 MSK
Unique Paths
Links
Code
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
@cache
def dp(row: int, col: int) -> int:
if not 0 <= row < m or not 0 <= col < n:
return 0
if row == m - 1 and col == n - 1:
return 1
return dp(row + 1, col) + dp(row, col + 1)
return dp(0, 0)
1293 - 2023-09-02 16:26:14 +0300 MSK
Rotate Image
Links
Code
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
side_length = len(matrix)
for row in range(side_length // 2):
matrix[row], matrix[-row-1] = matrix[-row-1], matrix[row]
for i in range(side_length):
for j in range(i):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
1294 - 2023-09-02 10:50:42 +0300 MSK
Extra Characters in a String
Links
Code
class Solution:
def minExtraChar(self, s: str, dictionary: List[str]) -> int:
chars_count = len(s)
@cache
def dp(i: int) -> int:
chars_left = chars_count - i
if chars_left == 0:
return 0
min_extra_chars = chars_left
for word in dictionary:
word_length = len(word)
if word_length > chars_left or s[i:i+word_length] != word:
continue
if word_length == chars_left:
return 0
min_extra_chars = min(min_extra_chars, dp(i + word_length))
return min(min_extra_chars, 1 + dp(i + 1))
return dp(0)
1295 - 2023-09-01 18:41:17 +0300 MSK
Text Justification
Links
Code
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
words_count = len(words)
def get_line(word_idx: int) -> Tuple[List[str], int]:
line = []
line_length = 0
for i in range(word_idx, words_count):
word = words[i]
word_length = len(word)
if line_length + word_length > maxWidth:
break
line.append(word)
line_length += word_length + 1
return line, line_length
def create_line(line: List[str], line_length: int, word_idx: int) -> str:
base_length = line_length - 1
extra_spaces = maxWidth - base_length
if len(line) == 1 or word_idx == words_count:
return " ".join(line) + " " * extra_spaces
word_count = len(line) - 1
spaces_per_word = extra_spaces // word_count
needs_extra_space = extra_spaces % word_count
for j in range(needs_extra_space):
line[j] += " "
for j in range(word_count):
line[j] += " " * spaces_per_word
return " ".join(line)
result = []
i = 0
while i < words_count:
line, line_length = get_line(i)
i += len(line)
result.append(create_line(line, line_length, i))
return result
1296 - 2023-09-01 18:38:28 +0300 MSK
Course Schedule
Links
Code
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
nodes = [[] for _ in range(numCourses)]
for target, required in prerequisites:
nodes[target].append(required)
visited = set()
@cache
def dfs(course: int) -> bool:
if course in visited:
return False
edges = nodes[course]
if not edges:
return True
visited.add(course)
return all(dfs(edge) for edge in edges)
for course in range(numCourses):
if not dfs(course):
return False
visited.clear()
return True
1297 - 2023-09-01 18:37:48 +0300 MSK
Course Schedule
Links
Code
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
nodes = [[] for _ in range(numCourses)]
for target, required in prerequisites:
nodes[target].append(required)
visited = set()
@cache
def dfs(course: int) -> bool:
if course in visited:
return False
edges = nodes[course]
if not edges:
return True
visited.add(course)
return all(dfs(edge) for edge in edges)
for course in range(numCourses):
if not dfs(course):
return False
visited.clear()
return True
1298 - 2023-09-01 09:58:21 +0300 MSK
Counting Bits
Links
Code
class Solution:
def countBits(self, n: int) -> List[int]:
ans = [0] * (n + 1)
for i in range(1, n + 1):
ans[i] = ans[i >> 1] + (i & 1)
return ans
1299 - 2023-09-01 09:55:13 +0300 MSK
Counting Bits
Links
Code
class Solution:
def countBits(self, n: int) -> List[int]:
return tuple(bin(i).count("1") for i in range(n + 1))
1300 - 2023-08-31 22:14:58 +0300 MSK
Evaluate Division
Links
Code
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
equations_count = len(equations)
queries_count = len(queries)
edges = defaultdict(dict)
seen_nodes = set()
invalid = -1.0
def dfs(val1: str, val2: str) -> float:
if val1 == val2:
return 1.0
if val2 in edges[val1]:
return edges[val1][val2]
if val1 in seen_nodes:
return invalid
seen_nodes.add(val1)
for connected_node in edges[val1]:
new_edge_res = dfs(connected_node, val2)
if new_edge_res == invalid:
continue
new_edge_res *= edges[val1][connected_node]
edges[val1][val2] = new_edge_res
return new_edge_res
return invalid
for i in range(equations_count):
(val1, val2), res = equations[i], values[i]
edges[val1][val2], edges[val2][val1] = res, 1 / res
for i in range(queries_count):
res, (val1, val2) = -1, queries[i]
if val1 in edges and val2 in edges:
seen_nodes.clear()
res = dfs(val1, val2)
queries[i] = res
return queries
1301 - 2023-08-31 20:45:02 +0300 MSK
Clone Graph
Links
Code
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
old_to_new = {}
def clone(node: Node) -> Node:
if node in old_to_new:
return old_to_new[node]
new_node = Node(node.val)
old_to_new[node] = new_node
new_node.neighbors = [clone(neighbor) for neighbor in node.neighbors]
return new_node
return clone(node) if node else node
1302 - 2023-08-31 20:35:52 +0300 MSK
Surrounded Regions
Links
Code
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
row_count, col_count = len(board), len(board[0])
moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
ignore_cells = set()
def bfs(row: int, col: int) -> None:
if not 0 <= row < row_count or not 0 <= col < col_count:
return
if (row, col) in ignore_cells or board[row][col] == "X":
return
ignore_cells.add((row, col))
for row_delta, col_delta in moves:
bfs(row + row_delta, col + col_delta)
for row, col in itertools.chain(
((0, col) for col in range(col_count)),
((row_count - 1, col) for col in range(col_count)),
((row, 0) for row in range(row_count)),
((row, col_count - 1) for row in range(row_count))
):
bfs(row, col)
for row in range(1, row_count - 1):
for col in range(1, col_count - 1):
if (row, col) in ignore_cells:
continue
board[row][col] = "X"
1303 - 2023-08-31 20:35:00 +0300 MSK
Surrounded Regions
Links
Code
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
row_count, col_count = len(board), len(board[0])
moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
ignore_stack = set()
def bfs(row: int, col: int) -> None:
if not 0 <= row < row_count or not 0 <= col < col_count:
return
if (row, col) in ignore_stack or board[row][col] == "X":
return
ignore_stack.add((row, col))
for row_delta, col_delta in moves:
bfs(row + row_delta, col + col_delta)
for row, col in itertools.chain(
((0, col) for col in range(col_count)),
((row_count - 1, col) for col in range(col_count)),
((row, 0) for row in range(row_count)),
((row, col_count - 1) for row in range(row_count))
):
bfs(row, col)
flip_x = True
for row in range(1, row_count - 1):
for col in range(1, col_count - 1):
if (row, col) in ignore_stack:
continue
board[row][col] = "X"
1304 - 2023-08-31 20:34:31 +0300 MSK
Surrounded Regions
Links
Code
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
row_count, col_count = len(board), len(board[0])
moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
ignore_stack = set()
@cache
def bfs(row: int, col: int) -> None:
if not 0 <= row < row_count or not 0 <= col < col_count:
return
if (row, col) in ignore_stack or board[row][col] == "X":
return
ignore_stack.add((row, col))
for row_delta, col_delta in moves:
bfs(row + row_delta, col + col_delta)
for row, col in itertools.chain(
((0, col) for col in range(col_count)),
((row_count - 1, col) for col in range(col_count)),
((row, 0) for row in range(row_count)),
((row, col_count - 1) for row in range(row_count))
):
bfs(row, col)
flip_x = True
for row in range(1, row_count - 1):
for col in range(1, col_count - 1):
if (row, col) in ignore_stack:
continue
board[row][col] = "X"
1305 - 2023-08-31 15:29:43 +0300 MSK
Minimum Number of Taps to Open to Water a Garden
Links
Code
class Solution:
def minTaps(self, n: int, ranges: List[int]) -> int:
inf = float("inf")
dp = [inf] * (n + 1)
dp[0] = 0
for i in range(n + 1):
cur_range = ranges[i]
tap_start, tap_end = max(0, i - cur_range), min(n, i + cur_range)
for j in range(tap_start, tap_end + 1):
dp[tap_end] = min(dp[tap_end], dp[j] + 1)
min_taps = dp[n]
return -1 if min_taps == inf else min_taps
1306 - 2023-08-31 12:14:40 +0300 MSK
Minimum Number of Taps to Open to Water a Garden
Links
Code
class Solution:
def minTaps(self, n: int, ranges: List[int]) -> int:
arr = [0] * (n + 1)
for i, r in enumerate(ranges):
if r == 0:
continue
left = max(0, i - r)
arr[left] = max(arr[left], i + r)
end, far_can_reach, cnt = 0, 0, 0
for i, reach in enumerate(arr):
if i > end:
if far_can_reach <= end:
return -1
end, cnt = far_can_reach, cnt + 1
far_can_reach = max(far_can_reach, reach)
return cnt + (end < n)
1307 - 2023-08-30 19:06:25 +0300 MSK
Minimum Replacements to Sort the Array
Links
Code
class Solution:
def minimumReplacement(self, nums: List[int]) -> int:
nums_count = len(nums)
operations_count = 0
for i in reversed(range(nums_count - 1)):
cur, prev = nums[i], nums[i+1]
if cur <= prev:
continue
elements_count = (cur + prev - 1) // prev
operations_count += elements_count - 1
nums[i] //= elements_count
return operations_count
1308 - 2023-08-29 19:00:49 +0300 MSK
Number of Islands
Links
Code
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row_count, col_count = len(grid), len(grid[0])
island_count = 0
moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
@cache
def dfs(row: int, col: int) -> None:
if not 0 <= row < row_count or not 0 <= col < col_count or grid[row][col] == "0":
return
grid[row][col] = "0"
for row_delta, col_delta in moves:
dfs(row + row_delta, col + col_delta)
for row in range(row_count):
for col in range(col_count):
if grid[row][col] == "0":
continue
dfs(row, col)
island_count += 1
return island_count
1309 - 2023-08-29 18:48:22 +0300 MSK
Number of Islands
Links
Code
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row_count, col_count = len(grid), len(grid[0])
island_count = 0
moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
queue = set((row, col)
for row in range(row_count)
for col in range(col_count)
if grid[row][col] == "1")
@cache
def remove_island(row: int, col: int) -> None:
if not 0 <= row < row_count or not 0 <= col < col_count:
return
for row_delta, col_delta in moves:
new_cell = (row + row_delta, col + col_delta)
if new_cell in queue:
queue.remove(new_cell)
remove_island(*new_cell)
while queue:
remove_island(*queue.pop())
island_count += 1
return island_count
1310 - 2023-08-29 18:48:09 +0300 MSK
Number of Islands
Links
Code
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row_count, col_count = len(grid), len(grid[0])
island_count = 0
moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
queue = set((row, col)
for row in range(row_count)
for col in range(col_count)
if grid[row][col] == "1")
@cache
def remove_island(row: int, col: int) -> None:
if not 0 <= row < row_count or not 0 <= col < col_count:
return
for row_delta, col_delta in moves:
new_cell = (row + row_delta, col + col_delta)
if new_cell in queue:
queue.remove(new_cell)
remove_island(*new_cell)
while queue:
remove_island(*queue.pop())
island_count += 1
return island_count
1311 - 2023-08-29 18:44:17 +0300 MSK
Number of Islands
Links
Code
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row_count, col_count = len(grid), len(grid[0])
island_count = 0
moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
queue = set((row, col)
for row in range(row_count)
for col in range(col_count)
if grid[row][col] == "1")
def remove_island(row: int, col: int) -> None:
if not 0 <= row < row_count or not 0 <= col < col_count or (row, col) not in queue:
return
queue.remove((row, col))
for row_delta, col_delta in moves:
remove_island(row + row_delta, col + col_delta)
while queue:
remove_island(*next(iter(queue)))
island_count += 1
return island_count
1312 - 2023-08-29 18:43:22 +0300 MSK
Number of Islands
Links
Code
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row_count, col_count = len(grid), len(grid[0])
island_count = 0
moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
queue = set((row, col)
for row in range(row_count)
for col in range(col_count)
if grid[row][col] == "1")
@cache
def remove_island(row: int, col: int) -> None:
if not 0 <= row < row_count or not 0 <= col < col_count or (row, col) not in queue:
return
queue.remove((row, col))
for row_delta, col_delta in moves:
remove_island(row + row_delta, col + col_delta)
while queue:
remove_island(*next(iter(queue)))
island_count += 1
return island_count
1313 - 2023-08-29 11:50:54 +0300 MSK
Minimum Penalty for a Shop
Links
Code
class Solution:
def bestClosingTime(self, customers: str) -> int:
# Start with closing at hour 0, the penalty equals all 'Y' in closed hours.
cur_penalty = min_penalty = customers.count("Y")
earliest_hour = 0
for hour, customer in enumerate(customers):
# If status in hour i is 'Y', moving it to open hours decrement
# penalty by 1. Otherwise, moving 'N' to open hours increment
# penatly by 1.
cur_penalty += 1 if customer == "N" else -1
# Update earliest_hour if a smaller penatly is encountered
if cur_penalty < min_penalty:
earliest_hour = hour + 1
min_penalty = cur_penalty
return earliest_hour
1314 - 2023-08-28 13:37:58 +0300 MSK
Map Sum Pairs
Links
Code
class MapSum:
def __init__(self):
self._map = {}
def insert(self, key: str, val: int) -> None:
self._map[key] = val
def sum(self, prefix: str) -> int:
return sum(value for key, value in self._map.items() if key.startswith(prefix))
# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)
1315 - 2023-08-28 13:35:54 +0300 MSK
Implement Stack using Queues
Links
Code
class MyStack:
def __init__(self):
self._queue = []
def push(self, x: int) -> None:
self._queue.append(x)
def pop(self) -> int:
return self._queue.pop()
def top(self) -> int:
return self._queue[-1]
def empty(self) -> bool:
return len(self._queue) == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
1316 - 2023-08-27 18:09:36 +0300 MSK
Minimum Absolute Difference in BST
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
def min_node_diff(node: TreeNode, low: int, high: int) -> int:
if not node:
return high - low
return min(min_node_diff(node.left, low, node.val),
min_node_diff(node.right, node.val, high))
return min_node_diff(root, -maxsize, maxsize)
1317 - 2023-08-27 18:03:23 +0300 MSK
Minimum Absolute Difference in BST
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
values = []
def fall(node: TreeNode) -> None:
if not node:
return
values.append(node.val)
if node.left:
fall(node.left)
if node.right:
fall(node.right)
fall(root)
values.sort()
min_diff = abs(values[1] - values[0])
for i in range(1, len(values) - 1):
min_diff = min(min_diff, abs(values[i] - values[i+1]))
return min_diff
1318 - 2023-08-27 17:55:09 +0300 MSK
Frog Jump
Links
Code
class Solution:
def canCross(self, stones: List[int]) -> bool:
m = set(stones)
@cache
def dfs(i, j):
if i == stones[-1]: return True
return any(x and x + i in m and dfs(x + i, x) for x in range(j - 1, j + 2))
return dfs(0, 0)
1319 - 2023-08-26 16:17:44 +0300 MSK
Count Complete Tree Nodes
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
def left_height(root: TreeNode) -> int:
return 0 if not root else 1 + left_height(root.left)
def right_height(root: TreeNode) -> int:
return 0 if not root else 1 + right_height(root.right)
left, right = left_height(root), right_height(root)
if left > right:
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
return 2**left - 1
1320 - 2023-08-26 16:17:28 +0300 MSK
Count Complete Tree Nodes
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
def left_height(root: TreeNode) -> int:
return 0 if not root else 1 + left_height(root.left)
def right_height(root: TreeNode) -> int:
return 0 if not root else 1+ right_height(root.right)
left, right = left_height(root), right_height(root)
if left > right:
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
return 2**left - 1
1321 - 2023-08-26 16:16:46 +0300 MSK
Count Complete Tree Nodes
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
def left_height(root: TreeNode) -> int:
return 0 if not root else 1 + left_height(root.left)
def right_height(root: TreeNode) -> int:
return 0 if not root else 1+ right_height(root.right)
left, right = left_height(root), right_height(root)
if left > right:
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
return 2**left - 1
1322 - 2023-08-26 16:06:04 +0300 MSK
Path Sum
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
node_stack = [(root, 0)]
while node_stack:
node, curr_sum = node_stack.pop()
if not node:
continue
new_sum = curr_sum + node.val
if new_sum == targetSum and not node.left and not node.right:
return True
node_stack.extend(((node.left, new_sum), (node.right, new_sum)))
return False
1323 - 2023-08-26 15:38:12 +0300 MSK
Symmetric Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
comparison_stack = [(root.left, root.right)]
while comparison_stack:
left, right = comparison_stack.pop()
if not left and not right:
continue
if not left or not right or left.val != right.val:
return False
comparison_stack.extend(((left.left, right.right), (left.right, right.left)))
return True
1324 - 2023-08-26 15:24:31 +0300 MSK
Symmetric Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
return self.check(root.left, root.right)
def check(self, left: TreeNode, right: TreeNode) -> bool:
if not left and not right:
return True
if not left or not right or left.val != right.val:
return False
return self.check(left.left, right.right) and self.check(left.right, right.left)
1325 - 2023-08-26 15:20:18 +0300 MSK
Invert Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
1326 - 2023-08-26 15:20:08 +0300 MSK
Invert Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
1327 - 2023-08-26 15:19:33 +0300 MSK
Invert Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
1328 - 2023-08-26 15:18:57 +0300 MSK
Invert Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
self.invertTree(root.left)
self.invertTree(root.right)
root.left, root.right = root.right, root.left
return root
1329 - 2023-08-26 12:16:27 +0300 MSK
Maximum Length of Pair Chain
Links
Code
class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs_count = len(pairs)
if pairs_count < 2:
return pairs_count
pairs.sort()
@cache
def dp(curr_pair: int) -> int:
right = pairs[curr_pair][1]
max_length = 1
for new_pair in range(curr_pair + 1, pairs_count):
new_left = pairs[new_pair][0]
new_length = dp(new_pair) + (1 if new_left > right else 0)
if new_length > max_length:
max_length = new_length
return max_length
return dp(0)
1330 - 2023-08-25 10:04:50 +0300 MSK
Interleaving String
Links
Code
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
length_1, length_2, length_3 = len(s1), len(s2), len(s3)
if length_1 + length_2 != length_3:
return False
@cache
def dp(i_1: int, i_2: int, i_3: int) -> bool:
if i_3 == length_3:
return True
target = s3[i_3]
return (
i_1 != length_1 and s1[i_1] == target and dp(i_1 + 1, i_2, i_3 + 1)
) or (
i_2 != length_2 and s2[i_2] == target and dp(i_1, i_2 + 1, i_3 + 1)
)
return dp(0, 0, 0)
1331 - 2023-08-24 16:42:07 +0300 MSK
Find K Pairs with Smallest Sums
Links
Code
class Solution:
def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
nums1_count, nums2_count = len(nums1), len(nums2)
result = []
visited = set(((0, 0)))
min_heap = [(nums1[0] + nums2[0], (0, 0))]
count = 0
while k > 0 and min_heap:
_, (i, j) = heappop(min_heap)
new_i, new_j = i + 1, j + 1
new_pair1, new_pair2 = (new_i, j), (i, new_j)
num1, num2 = nums1[i], nums2[j]
result.append((num1, num2))
if new_i < nums1_count and new_pair1 not in visited:
heappush(min_heap, (nums1[new_i] + num2, new_pair1))
visited.add(new_pair1)
if new_j < nums2_count and new_pair2 not in visited:
heappush(min_heap, (num1 + nums2[new_j], new_pair2))
visited.add(new_pair2)
k -= 1
return result
1332 - 2023-08-24 13:45:42 +0300 MSK
Text Justification
Links
Code
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
words_count = len(words)
def get_line(word_idx: int) -> Tuple[List[str], int]:
line = []
line_length = 0
for i in range(word_idx, words_count):
word = words[i]
word_length = len(word)
if line_length + word_length > maxWidth:
break
line.append(word)
line_length += word_length + 1
return line, line_length
def create_line(line: List[str], line_length: int, word_idx: int) -> str:
base_length = line_length - 1
extra_spaces = maxWidth - base_length
if len(line) == 1 or word_idx == words_count:
return " ".join(line) + " " * extra_spaces
word_count = len(line) - 1
spaces_per_word = extra_spaces // word_count
needs_extra_space = extra_spaces % word_count
for j in range(needs_extra_space):
line[j] += " "
for j in range(word_count):
line[j] += " " * spaces_per_word
return " ".join(line)
result = []
i = 0
while i < words_count:
line, line_length = get_line(i)
i += len(line)
result.append(create_line(line, line_length, i))
return result
1333 - 2023-08-23 22:56:37 +0300 MSK
Summary Ranges
Links
Code
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
nums_count = len(nums)
if nums_count == 0:
return []
if nums_count == 1:
return [str(nums[0])]
ranges = [[nums[0]] * 2]
for i, num in enumerate(nums[1:]):
if ranges[-1][1] == num - 1:
ranges[-1][1] = num
else:
ranges.append([num, num])
return [f"{start}->{end}" if start != end else str(start) for start, end in ranges]
1334 - 2023-08-23 12:45:05 +0300 MSK
Reorganize String
Links
Code
class Solution:
def reorganizeString(self, s: str) -> str:
result = []
# Min heap ordered by character counts, so we will use
# negative values for count
priority_queue = [(-count, char) for char, count in Counter(s).items()]
heapify(priority_queue)
while priority_queue:
count_first, char_first = heappop(priority_queue)
if not result or char_first != result[-1]:
result.append(char_first)
if count_first != -1:
heappush(priority_queue, (count_first + 1, char_first))
continue
if not priority_queue:
return ""
count_second, char_second = heappop(priority_queue)
result.append(char_second)
if count_second != -1:
heappush(priority_queue, (count_second + 1, char_second))
heappush(priority_queue, (count_first, char_first))
return "".join(result)
1335 - 2023-08-22 10:32:27 +0300 MSK
Excel Sheet Column Title
Links
Code
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
result = []
while columnNumber:
columnNumber, remainder = divmod(columnNumber - 1, 26)
result.append(chr(65 + remainder))
return ''.join(reversed(result))
1336 - 2023-08-21 23:38:46 +0300 MSK
Spiral Matrix
Links
Code
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
row_count, col_count = len(matrix), len(matrix[0])
if row_count == 1:
return matrix[0]
if col_count == 1:
return [row[0] for row in matrix]
result = []
top, bot, left, right = 0, row_count - 1, 0, col_count - 1
capacity = row_count * col_count
while len(result) < capacity:
for col in range(left, right + 1):
result.append(matrix[top][col])
top += 1
for row in range(top, bot + 1):
result.append(matrix[row][right])
right -= 1
if top <= bot:
for col in range(right, left - 1, -1):
result.append(matrix[bot][col])
bot -= 1
if left <= right:
for row in range(bot, top - 1, -1):
result.append(matrix[row][left])
left += 1
return result
1337 - 2023-08-21 21:08:48 +0300 MSK
Valid Sudoku
Links
Code
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
row_count, column_count = 9, 9
row_counters = [defaultdict(bool) for _ in range(row_count)]
column_counters = [defaultdict(bool) for _ in range(column_count)]
subbox_counters = [[defaultdict(bool) for _ in range(column_count//3)]
for _ in range(row_count//3)]
for row in range(row_count):
for column in range(column_count):
char = board[row][column]
if char == ".":
continue
counters = (
row_counters[row], column_counters[column],
subbox_counters[row//3][column//3]
)
for counter in counters:
if counter[char]:
return False
counter[char] = True
return True
1338 - 2023-08-21 21:08:11 +0300 MSK
Valid Sudoku
Links
Code
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
row_count, column_count = 9, 9
row_counters = [defaultdict(bool) for _ in range(row_count)]
column_counters = [defaultdict(bool) for _ in range(column_count)]
subbox_counters = [[defaultdict(bool) for _ in range(column_count//3)]
for _ in range(row_count//3)]
for row in range(row_count):
for column in range(column_count):
char = board[row][column]
if char == ".":
continue
counters = (
row_counters[row], column_counters[column],
subbox_counters[row//3][column//3]
)
for counter in counters:
if counter[char]:
return False
counter[char] = True
return True
1339 - 2023-08-21 09:29:54 +0300 MSK
Repeated Substring Pattern
Links
Code
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
length = len(s)
for i in range(1, length // 2 + 1):
if length % i != 0:
continue
if s == s[:i] * (length // i):
return True
return False
1340 - 2023-08-20 14:34:41 +0300 MSK
Sort Items by Groups Respecting Dependencies
Links
Code
class Solution:
def sortItems(self, n, m, group, beforeItems):
# If an item belongs to zero group, assign it a unique group id.
group_id = m
for i in range(n):
if group[i] == -1:
group[i] = group_id
group_id += 1
# Sort all item regardless of group dependencies.
item_graph = [[] for _ in range(n)]
item_indegree = [0] * n
# Sort all groups regardless of item dependencies.
group_graph = [[] for _ in range(group_id)]
group_indegree = [0] * group_id
for curr in range(n):
for prev in beforeItems[curr]:
# Each (prev -> curr) represents an edge in the item graph.
item_graph[prev].append(curr)
item_indegree[curr] += 1
# If they belong to different groups, add an edge in the group graph.
if group[curr] != group[prev]:
group_graph[group[prev]].append(group[curr])
group_indegree[group[curr]] += 1
# Tologlogical sort nodes in graph, return [] if a cycle exists.
def topologicalSort(graph, indegree):
visited = []
stack = [node for node in range(len(graph)) if indegree[node] == 0]
while stack:
cur = stack.pop()
visited.append(cur)
for neib in graph[cur]:
indegree[neib] -= 1
if indegree[neib] == 0:
stack.append(neib)
return visited if len(visited) == len(graph) else []
item_order = topologicalSort(item_graph, item_indegree)
group_order = topologicalSort(group_graph, group_indegree)
if not item_order or not group_order:
return []
# Items are sorted regardless of groups, we need to
# differentiate them by the groups they belong to.
ordered_groups = collections.defaultdict(list)
for item in item_order:
ordered_groups[group[item]].append(item)
# Concatenate sorted items in all sorted groups.
# [group 1, group 2, ... ] -> [(item 1, item 2, ...), (item 1, item 2, ...), ...]
answer = []
for group_index in group_order:
answer += ordered_groups[group_index]
return answer
1341 - 2023-08-19 18:48:22 +0300 MSK
Sorting Three Groups
Links
Code
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
nums_count = len(nums)
if nums_count == 1:
return 0
@cache
def dp(i: int, start_group: int) -> int:
if i == nums_count:
return 0
curr_group = nums[i] - 1
actions_min = None
for group_available in range(start_group, 3):
actions = dp(i + 1, group_available) + (0 if group_available == curr_group else 1)
if actions_min is None or actions < actions_min:
actions_min = actions
return actions_min
return dp(0, 0)
1342 - 2023-08-19 18:13:19 +0300 MSK
Make String a Subsequence Using Cyclic Increments
Links
Code
class Solution:
def canMakeSubsequence(self, str1: str, str2: str) -> bool:
length1, length2 = len(str1), len(str2)
for i in range(length1):
if i + length2 > length1:
break
idx2 = 0
for idx1 in range(i, length1):
if ord(str2[idx2]) - ord(str1[idx1]) in (0, 1, -25):
idx2 += 1
if idx2 == length2:
return True
return False
1343 - 2023-08-19 17:36:50 +0300 MSK
Count Pairs Whose Sum is Less than Target
Links
Code
class Solution:
def countPairs(self, nums: List[int], target: int) -> int:
pairs_count = 0
nums_count = len(nums)
for i in range(nums_count):
num1 = nums[i]
for j in range(i + 1, nums_count):
if num1 + nums[j] < target:
pairs_count += 1
return pairs_count
1344 - 2023-08-19 17:13:39 +0300 MSK
Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
Links
Code
class Solution:
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.max_size = 1
def find(self, x):
# Finds the root of x
if x != self.parent[x]:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
# Connects x and y
root_x = self.find(x)
root_y = self.find(y)
if root_x != root_y:
if self.size[root_x] < self.size[root_y]:
root_x, root_y = root_y, root_x
self.parent[root_y] = root_x
self.size[root_x] += self.size[root_y]
self.max_size = max(self.max_size, self.size[root_x])
return True
return False
def findCriticalAndPseudoCriticalEdges(self, n, edges):
new_edges = [edge.copy() for edge in edges]
# Add index to edges for tracking
for i, edge in enumerate(new_edges):
edge.append(i)
# Sort edges based on weight
new_edges.sort(key=lambda x: x[2])
# Find MST weight using union-find
uf_std = self.UnionFind(n)
std_weight = 0
for u, v, w, _ in new_edges:
if uf_std.union(u, v):
std_weight += w
# Check each edge for critical and pseudo-critical
critical = []
pseudo_critical = []
for (u, v, w, i) in new_edges:
# Ignore this edge and calculate MST weight
uf_ignore = self.UnionFind(n)
ignore_weight = 0
for (x, y, w_ignore, j) in new_edges:
if i != j and uf_ignore.union(x, y):
ignore_weight += w_ignore
# If the graph is disconnected or the total weight is greater,
# the edge is critical
if uf_ignore.max_size < n or ignore_weight > std_weight:
critical.append(i)
continue
# Force this edge and calculate MST weight
uf_force = self.UnionFind(n)
force_weight = w
uf_force.union(u, v)
for (x, y, w_force, j) in new_edges:
if i != j and uf_force.union(x, y):
force_weight += w_force
# If total weight is the same, the edge is pseudo-critical
if force_weight == std_weight:
pseudo_critical.append(i)
return [critical, pseudo_critical]
1345 - 2023-08-18 10:52:33 +0300 MSK
Maximal Network Rank
Links
Code
class Solution:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
city_roads = [set() for _ in range(n)]
for city_one, city_two in roads:
city_roads[city_one].add(city_two)
city_roads[city_two].add(city_one)
max_rank = 0
for city_one in range(n):
for city_two in range(city_one + 1, n):
rank = len(city_roads[city_one]) + len(city_roads[city_two])
if city_one in city_roads[city_two]:
rank -= 1
if rank > max_rank:
max_rank = rank
return max_rank
1346 - 2023-08-17 16:52:59 +0300 MSK
01 Matrix
Links
Code
class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
if not mat or not mat[0]:
return []
row_count, column_count = len(mat), len(mat[0])
queue = set()
MAX_VALUE = row_count * column_count
# Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.
for row in range(row_count):
for column in range(column_count):
if mat[row][column] == 0:
queue.add((row, column))
else:
mat[row][column] = MAX_VALUE
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
while queue:
center_row, center_column = queue.pop()
distance_from_center = mat[center_row][center_column] + 1
for delta_row, delta_column in directions:
new_row, new_column = center_row + delta_row, center_column + delta_column
if not 0 <= new_row < row_count or not 0 <= new_column < column_count:
continue
if mat[new_row][new_column] > distance_from_center:
queue.add((new_row, new_column))
mat[new_row][new_column] = distance_from_center
return mat
1347 - 2023-08-16 14:36:21 +0300 MSK
Sliding Window Maximum
Links
Code
import sortedcontainers
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
nums_count = len(nums)
if nums_count <= k:
return [max(nums)]
counter = defaultdict(int)
elems = sortedcontainers.SortedSet()
for num in nums[:k]:
counter[num] += 1
elems.add(num)
result = [elems[-1]]
for i in range(k, nums_count):
new_num = nums[i]
remove_num = nums[i-k]
counter[new_num] += 1
elems.add(new_num)
counter[remove_num] -= 1
if counter[remove_num] == 0:
elems.discard(remove_num)
result.append(elems[-1])
return result
1348 - 2023-08-15 17:06:49 +0300 MSK
Partition List
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
before_head, after_head = ListNode(0), ListNode(0)
before_tail, after_tail = before_head, after_head
while head:
if head.val < x:
before_tail.next, before_tail = head, head
else:
after_tail.next, after_tail = head, head
head = head.next
after_tail.next, before_tail.next = None, after_head.next
return before_head.next
1349 - 2023-08-15 17:02:49 +0300 MSK
Partition List
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
first_left, last_left, first_right, last_right = None, None, None, None
while head:
is_left = head.val < x
is_right = not is_left
next_node = head.next
head.next = first_right if is_left else None
if is_left and last_left:
last_left.next = head
last_left = head
elif is_left and not first_left:
first_left, last_left = head, head
if is_right and first_right:
last_right.next = head
last_right = head
elif is_right and not first_right:
first_right, last_right = head, head
if last_left:
last_left.next = head
head = next_node
return first_left if first_left else first_right
1350 - 2023-08-14 11:17:39 +0300 MSK
Kth Largest Element in an Array
Links
Code
class Solution:
def findKthLargest(self, nums, k):
heap = []
for num in nums:
heapq.heappush(heap, num)
if len(heap) > k:
heapq.heappop(heap)
return heap[0]
1351 - 2023-08-13 18:35:13 +0300 MSK
Check if There is a Valid Partition For The Array
Links
Code
class Solution:
def validPartition(self, nums: List[int]) -> bool:
n = len(nums)
dp = [True] + [False] * n
# Determine if the prefix array nums[0 ~ i] has a valid partition
for i in range(n):
dp_index = i + 1
# Check 3 possibilities
if i > 0 and nums[i] == nums[i - 1]:
dp[dp_index] |= dp[dp_index - 2]
if i > 1 and nums[i] == nums[i - 1] == nums[i - 2]:
dp[dp_index] |= dp[dp_index - 3]
if i > 1 and nums[i] == nums[i - 1] + 1 == nums[i - 2] + 2:
dp[dp_index] |= dp[dp_index - 3]
return dp[n]
1352 - 2023-08-12 17:50:41 +0300 MSK
Unique Paths II
Links
Code
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
row_count = len(obstacleGrid)
column_count = len(obstacleGrid[0])
if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1:
return 0
dp = [[0] * column_count for _ in range(row_count)]
dp[0][0] = 1
for column in range(1, column_count):
if obstacleGrid[0][column] == 1:
break
dp[0][column] = dp[0][column-1]
for row in range(1, row_count):
if obstacleGrid[row][0] == 0:
dp[row][0] = dp[row-1][0]
for column in range(1, column_count):
if obstacleGrid[row][column] == 1:
continue
dp[row][column] = dp[row-1][column] + dp[row][column-1]
return dp[-1][-1]
1353 - 2023-08-11 17:52:07 +0300 MSK
3Sum
Links
Code
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = set()
#1. Split nums into three lists: negative numbers, positive numbers, and zeros
negatives, positives, zeros = [], [], []
for num in nums:
if num > 0:
positives.append(num)
elif num < 0:
negatives.append(num)
else:
zeros.append(num)
#2. Create a separate set for negatives and positives for O(1) look-up times
negatives_count, positives_count, zeros_count = len(negatives), len(positives), len(zeros)
negatives_set, positives_set = set(negatives), set(positives)
#3. If there is at least 1 zero in the list, add all cases where -num exists in N and num exists in P
# i.e. (-3, 0, 3) = 0
for num in positives_set if zeros else []:
negative = -1 * num
if negative in negatives_set:
result.add((negative, 0, num))
#3. If there are at least 3 zeros in the list then also include (0, 0, 0) = 0
if zeros_count >= 3:
result.add((0, 0, 0))
#4. For all pairs of negative numbers (-3, -1), check to see if their complement (4)
# exists in the positive number set
for i in range(negatives_count):
negative_1 = negatives[i]
for j in range(i + 1, negatives_count):
negative_2 = negatives[j]
target = -1 * (negative_1 + negative_2)
if target in positives_set:
result.add(tuple(sorted([negative_1, negative_2, target])))
#5. For all pairs of positive numbers (1, 1), check to see if their complement (-2)
# exists in the negative number set
for i in range(positives_count):
positive_1 = positives[i]
for j in range(i + 1, positives_count):
positive_2 = positives[j]
target = -1 * (positive_1 + positive_2)
if target in negatives_set:
result.add(tuple(sorted([positive_1, positive_2, target])))
return result
1354 - 2023-08-11 12:05:33 +0300 MSK
Product of Array Except Self
Links
Code
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
nums_count = len(nums)
result = [1] * nums_count
prefix = 1
postfix = 1
for i in range(nums_count):
result[i] *= prefix
prefix *= nums[i]
from_end = -1 * (i + 1)
result[from_end] *= postfix
postfix *= nums[from_end]
return result
1355 - 2023-08-11 12:01:50 +0300 MSK
Product of Array Except Self
Links
Code
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
nums_count = len(nums)
result = [1] * nums_count
prefix = 1
postfix = 1
for i in range(nums_count):
result[i] *= prefix
prefix *= nums[i]
result[nums_count-i-1] *= postfix
postfix *= nums[nums_count-i-1]
return result
1356 - 2023-08-11 11:17:35 +0300 MSK
Coin Change II
Links
Code
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
n = len(coins)
dp = [[0] * (amount + 1) for _ in range(n + 1)]
for i in range(n):
dp[i][0] = 1
for i in range(n - 1, -1, -1):
for j in range(1, amount + 1):
if coins[i] > j:
dp[i][j] = dp[i + 1][j]
else:
dp[i][j] = dp[i + 1][j] + dp[i][j - coins[i]]
return dp[0][amount]
1357 - 2023-08-11 11:12:31 +0300 MSK
Coin Change II
Links
Code
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
coins_count = len(coins)
memo = [[-1] * (amount + 1) for _ in range(coins_count)]
def dp(i: int, amount: int) -> int:
if amount == 0:
return 1
if i == coins_count:
return 0
if memo[i][amount] != -1:
return memo[i][amount]
value = None
if coins[i] > amount:
value = dp(i + 1, amount)
else:
value = dp(i, amount - coins[i]) + dp(i + 1, amount)
memo[i][amount] = value
return value
return dp(0, amount)
1358 - 2023-08-10 17:04:38 +0300 MSK
Search in Rotated Sorted Array II
Links
Code
class Solution:
def search(self, nums: List[int], target: int) -> bool:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return True
if nums[mid] == nums[left]:
left += 1
continue
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return False
1359 - 2023-08-09 15:13:28 +0300 MSK
Best Time to Buy and Sell Stock IV
Links
Code
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
# no transaction, no profit
if k == 0: return 0
# dp[k][0] = min cost you need to spend at most k transactions
# dp[k][1] = max profit you can achieve at most k transactions
dp = [[1000, 0] for _ in range(k + 1)]
for price in prices:
for i in range(1, k + 1):
# price - dp[i - 1][1] is how much you need to spend
# i.e use the profit you earned from previous transaction to buy the stock
# we want to minimize it
dp[i][0] = min(dp[i][0], price - dp[i - 1][1])
# price - dp[i][0] is how much you can achieve from previous min cost
# we want to maximize it
dp[i][1] = max(dp[i][1], price - dp[i][0])
# return max profit at most k transactions
# or you can write `return dp[-1][1]`
return dp[k][1]
1360 - 2023-08-09 12:05:47 +0300 MSK
Minimize the Maximum Difference of Pairs
Links
Code
class Solution:
def minimizeMax(self, nums: List[int], p: int) -> int:
nums.sort()
nums_count = len(nums)
# Find the number of valid pairs by greedy approach
def countValidPairs(threshold: int) -> int:
index, count = 0, 0
while index < nums_count - 1:
# If a valid pair is found, skip both numbers.
if nums[index + 1] - nums[index] <= threshold:
count += 1
index += 1
index += 1
return count
left, right = 0, nums[-1] - nums[0]
while left < right:
mid = left + (right - left) // 2
# If there are enough pairs, look for a smaller threshold.
# Otherwise, look for a larger threshold.
if countValidPairs(mid) >= p:
right = mid
else:
left = mid + 1
return left
1361 - 2023-08-08 23:40:50 +0300 MSK
Best Time to Buy and Sell Stock III
Links
Code
class Solution:
def maxProfit(self, prices: List[int]) -> int:
'''
dp_2_hold: max profit with 2 transactions, and in hold state
dp_2_not_hold: max profit with 2 transactions, and not in hold state
dp_1_hold: max profit with 1 transaction, and in hold state
dp_1_not_hold: max profit with 1 transaction, and not in hold state
Note: it is impossible to have stock in hand and sell on first day, therefore -infinity is set as initial profit value for hold state
'''
dp_2_hold, dp_2_not_hold = -float('inf'), 0
dp_1_hold, dp_1_not_hold = -float('inf'), 0
for stock_price in prices:
# either keep being in not-hold state, or sell with stock price today
dp_2_not_hold = max( dp_2_not_hold, dp_2_hold + stock_price )
# either keep being in hold state, or just buy with stock price today ( add one more transaction )
dp_2_hold = max( dp_2_hold, dp_1_not_hold - stock_price )
# either keep being in not-hold state, or sell with stock price today
dp_1_not_hold = max( dp_1_not_hold, dp_1_hold + stock_price )
# either keep being in hold state, or just buy with stock price today ( add one more transaction )
dp_1_hold = max( dp_1_hold, 0 - stock_price )
return dp_2_not_hold
1362 - 2023-08-08 23:36:48 +0300 MSK
Best Time to Buy and Sell Stock III
Links
Code
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
# initialize variables for first buy, first sell, second buy, and second sell
buy1, buy2 = float('inf'), float('inf')
sell1, sell2 = 0, 0
# iterate over prices to update buy and sell values
for price in prices:
# update first buy and sell values
buy1 = min(buy1, price)
sell1 = max(sell1, price - buy1)
# update second buy and sell values
buy2 = min(buy2, price - sell1)
sell2 = max(sell2, price - buy2)
return sell2
1363 - 2023-08-08 22:57:16 +0300 MSK
Longest Palindromic Substring
Links
Code
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
dp = [[False] * n for _ in range(n)]
ans = [0, 0]
for i in range(n):
dp[i][i] = True
for i in range(n - 1):
if s[i] == s[i + 1]:
dp[i][i + 1] = True
ans = [i, i + 1]
for diff in range(2, n):
for i in range(n - diff):
j = i + diff
if s[i] == s[j] and dp[i + 1][j - 1]:
dp[i][j] = True
ans = [i, j]
i, j = ans
return s[i:j + 1]
1364 - 2023-08-08 22:56:36 +0300 MSK
Maximal Square
Links
Code
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
row_count, column_count = len(matrix), len(matrix[0])
dp = [[0] * column_count for _ in range(row_count)]
max_size = 0
for column in range(column_count):
if matrix[0][column] == "0":
continue
dp[0][column] = 1
max_size = 1
for row in range(row_count):
if matrix[row][0] == "0":
continue
dp[row][0] = 1
max_size = 1
for row in range(1, row_count):
for column in range(1, column_count):
if matrix[row][column] == "0":
continue
value = min(dp[row-1][column], dp[row][column-1], dp[row-1][column-1]) + 1
dp[row][column] = value
max_size = max(max_size, value)
return max_size * max_size
1365 - 2023-08-08 21:50:31 +0300 MSK
Edit Distance
Links
Code
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
length1, length2 = len(word1), len(word2)
@cache
def dp(i1: int, i2: int) -> int:
if i1 == length1:
return length2 - (i2 + 1)
if i2 == length2:
return length1 - (i1 + 1)
if word1[i1] == word2[i2]:
return dp(i1 + 1, i2 + 1)
return 1 + min((
# replace or insert
dp(i1 + 1, i2 + 1),
# remove from i1
dp(i1 + 1, i2),
# remove from i2
dp(i1, i2 + 1)
))
return dp(0, 0) + 1
1366 - 2023-08-08 21:27:42 +0300 MSK
Interleaving String
Links
Code
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
length_1, length_2, length_3 = len(s1), len(s2), len(s3)
if length_1 + length_2 != length_3:
return False
@cache
def dp(i_1: int, i_2: int, i_3: int) -> bool:
if i_3 == length_3:
return True
target = s3[i_3]
return (
i_1 != length_1 and s1[i_1] == target and dp(i_1 + 1, i_2, i_3 + 1)
) or (
i_2 != length_2 and s2[i_2] == target and dp(i_1, i_2 + 1, i_3 + 1)
)
return dp(0, 0, 0)
1367 - 2023-08-08 21:02:11 +0300 MSK
Unique Paths II
Links
Code
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
row_count = len(obstacleGrid)
column_count = len(obstacleGrid[0])
if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1:
return 0
dp = [[0] * column_count for _ in range(row_count)]
dp[0][0] = 1
for column in range(1, column_count):
if obstacleGrid[0][column] == 1:
break
dp[0][column] = dp[0][column-1]
for row in range(1, row_count):
if obstacleGrid[row][0] == 0:
dp[row][0] = dp[row-1][0]
for column in range(1, column_count):
if obstacleGrid[row][column] == 1:
continue
dp[row][column] = dp[row-1][column] + dp[row][column-1]
return dp[-1][-1]
1368 - 2023-08-08 20:47:19 +0300 MSK
Unique Paths II
Links
Code
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
row_count = len(obstacleGrid)
column_count = len(obstacleGrid[0])
# dp = [[0] * column_count for _ in range(row_count)]
# for row in range(row_count):
# for column in range(column_count):
@cache
def dp(row: int, column: int) -> int:
if row == row_count or column == column_count or obstacleGrid[row][column] == 1:
return 0
if row == row_count - 1 and column == column_count - 1:
return 1
return dp(row + 1, column) + dp(row, column + 1)
return dp(0, 0)
1369 - 2023-08-08 20:31:21 +0300 MSK
Minimum Path Sum
Links
Code
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
row_count = len(grid)
column_count = len(grid[0]) if grid else None
if not row_count or not column_count:
return 0
dp = [[0] * column_count for _ in range(row_count)]
dp[0][0] = grid[0][0]
for column in range(1, column_count):
dp[0][column] = grid[0][column] + dp[0][column - 1]
for row in range(1, row_count):
dp[row][0] = grid[row][0] + dp[row - 1][0]
for column in range(1, column_count):
dp[row][column] = grid[row][column] + min(
dp[row - 1][column], dp[row][column-1]
)
# @cache
# def dp(row: int, column: int) -> int:
# if row == row_count or column == column_count:
# return 0
# return grid[row][column] + min(dp(row + 1, column), dp(row, column + 1))
#return dp(0, 0)
return dp[-1][-1]
1370 - 2023-08-08 19:53:50 +0300 MSK
Triangle
Links
Code
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
row_count = len(triangle)
dp = [[0] * row_count for _ in range(row_count)]
dp[0][0] = triangle[0][0]
for row in range(1, row_count):
dp[row][0] = triangle[row][0] + dp[row-1][0]
dp[row][row] = triangle[row][row] + dp[row-1][row-1]
for column in range(1, row):
dp[row][column] = triangle[row][column] + min(
dp[row-1][column], dp[row-1][column-1]
)
return min(dp[-1])
1371 - 2023-08-08 19:34:48 +0300 MSK
Triangle
Links
Code
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
row_count = len(triangle)
@cache
def dp(row: int, column: int) -> int:
if row == row_count or column == row + 1:
return 0
return triangle[row][column] + min(dp(row + 1, column), dp(row + 1, column + 1))
return dp(0, 0)
1372 - 2023-08-08 14:36:45 +0300 MSK
Kth Largest Element in an Array
Links
Code
class Solution:
def findKthLargest(self, nums, k):
heap = []
for num in nums:
heapq.heappush(heap, num)
if len(heap) > k:
heapq.heappop(heap)
return heap[0]
1373 - 2023-08-08 13:55:40 +0300 MSK
Search in Rotated Sorted Array
Links
Code
class Solution:
def search(self, nums: List[int], target: int) -> int:
nums_count = len(nums)
left, right = 0, len(nums) - 1
first_num, last_num = nums[0], nums[-1]
if first_num == target:
return 0
if last_num == target:
return nums_count - 1
# Find the index of the pivot element (the smallest element)
while left <= right:
mid = left + (right - left) // 2
if nums[mid] > last_num:
left = mid + 1
else:
right = mid - 1
pivot_num = nums[left]
if pivot_num == target:
return left
if pivot_num < target < last_num:
right = nums_count - 1
else:
left = 0
while left <= right:
mid = left + (right - left) // 2
mid_num = nums[mid]
if mid_num == target:
return mid
elif mid_num > target:
right = mid - 1
else:
left = mid + 1
return -1
1374 - 2023-08-08 13:55:01 +0300 MSK
Search in Rotated Sorted Array
Links
Code
class Solution:
def search(self, nums: List[int], target: int) -> int:
nums_count = len(nums)
left, right = 0, len(nums) - 1
first_num, last_num = nums[0], nums[-1]
if first_num == target:
return 0
if last_num == target:
return nums_count - 1
# Find the index of the pivot element (the smallest element)
while left <= right:
mid = left + (right - left) // 2
if nums[mid] > last_num:
left = mid + 1
else:
right = mid - 1
pivot_num = nums[left]
if pivot_num == target:
return left
if pivot_num < target < last_num:
right = nums_count - 1
else:
left = 0
while left <= right:
mid = (left + right) // 2
mid_num = nums[mid]
if mid_num == target:
return mid
elif mid_num > target:
right = mid - 1
else:
left = mid + 1
return -1
1375 - 2023-08-07 17:24:07 +0300 MSK
Longest Increasing Subsequence
Links
Code
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
nums_count = len(nums)
dp = [0] * nums_count
dp[0] = 1
for i in range(1, nums_count):
length = 0
start = nums[i]
for j in range(0, i):
if start > nums[j]:
length = max(length, dp[j])
dp[i] = 1 + length
return max(dp)
1376 - 2023-08-07 14:39:05 +0300 MSK
Coin Change
Links
Code
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for current_amount in range(1, amount + 1):
for coin in coins:
diff = current_amount - coin
if diff < 0:
continue
dp[current_amount] = min(dp[current_amount], dp[diff] + 1)
return dp[-1] if dp[-1] != amount + 1 else -1
1377 - 2023-08-07 14:27:07 +0300 MSK
Coin Change
Links
Code
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
if amount == 0:
return 0
@cache
def dp(coins_value: int) -> int:
if coins_value == amount:
return 0
if coins_value > amount:
return -1
min_coins_count = -1
for coin in coins:
new_count = 1 + dp(coin + coins_value)
if new_count == 0:
continue
if min_coins_count == -1 or new_count < min_coins_count:
min_coins_count = new_count
return min_coins_count
return dp(0)
1378 - 2023-08-07 13:27:10 +0300 MSK
Word Break
Links
Code
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
words = set(wordDict)
dp = [False] * (n + 1)
dp[0] = True
for i in range(1, n + 1):
for j in range(i):
if dp[j] and s[j:i] in words:
dp[i] = True
break
return dp[-1]
1379 - 2023-08-07 13:25:04 +0300 MSK
Word Break
Links
Code
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
@cache
def dp(i):
if i < 0:
return True
for word in wordDict:
if s[i - len(word) + 1:i + 1] == word and dp(i - len(word)):
return True
return False
return dp(len(s) - 1)
1380 - 2023-08-07 13:10:04 +0300 MSK
House Robber
Links
Code
class Solution:
def rob(self, nums: List[int]) -> int:
house_count = len(nums)
prev_1, prev_2 = 0, 0
for house in range(0, house_count):
prev_1, prev_2 = max(prev_2 + nums[house], prev_1), prev_1
return prev_1
1381 - 2023-08-07 13:07:20 +0300 MSK
House Robber
Links
Code
class Solution:
def rob(self, nums: List[int]) -> int:
house_count = len(nums)
dp = [0 for _ in range(house_count + 1)]
dp[1] = nums[0]
for house in range(1, house_count):
dp[house+1] = max(dp[house-1] + nums[house], dp[house])
return dp[-1]
1382 - 2023-08-07 12:57:18 +0300 MSK
House Robber
Links
Code
class Solution:
def rob(self, nums: List[int]) -> int:
house_count = len(nums)
@cache
def dp(house: int) -> int:
if house >= house_count:
return 0
return max(dp(house + 1), nums[house] + dp(house + 2))
return dp(0)
1383 - 2023-08-07 12:49:57 +0300 MSK
Climbing Stairs
Links
Code
class Solution:
def climbStairs(self, n: int) -> int:
if n < 3:
return n
minus_one, minus_two = 2, 1
for step in range(3, n + 1):
minus_one, minus_two = minus_one + minus_two, minus_one
return minus_one
1384 - 2023-08-07 12:45:54 +0300 MSK
Climbing Stairs
Links
Code
class Solution:
def climbStairs(self, n: int) -> int:
@cache
def dp(step: int) -> int:
if step <= 2:
return step
return dp(step - 1) + dp(step - 2)
return dp(n)
1385 - 2023-08-07 12:17:58 +0300 MSK
Search a 2D Matrix
Links
Code
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
length_vertical, length_horizontal = len(matrix), len(matrix[0])
left, right = 0, length_vertical - 1
while left <= right:
mid = left + (right - left) // 2
mid_number = matrix[mid][0]
if mid_number == target:
return True
if mid_number > target:
right = mid - 1
else:
left = mid + 1
vertical_index = right
left, right = 0, length_horizontal - 1
while left <= right:
mid = left + (right - left) // 2
mid_number = matrix[vertical_index][mid]
if mid_number == target:
return True
if mid_number > target:
right = mid - 1
else:
left = mid + 1
return False
1386 - 2023-08-06 18:05:41 +0300 MSK
Faulty Keyboard
Links
Code
class Solution:
def finalString(self, s: str) -> str:
result = []
for char in s:
if char == "i":
result.reverse()
else:
result.append(char)
return "".join(result)
1387 - 2023-08-06 18:00:12 +0300 MSK
Maximum Number of Events That Can Be Attended II
Links
Code
class Solution:
def maxValue(self, events: List[List[int]], k: int) -> int:
events.sort()
n = len(events)
starts = [start for start, end, value in events]
dp = [[-1] * n for _ in range(k + 1)]
def dfs(cur_index, count):
if count == 0 or cur_index == n:
return 0
if dp[count][cur_index] != -1:
return dp[count][cur_index]
# Find the nearest available event after attending event 0.
next_index = bisect_right(starts, events[cur_index][1])
dp[count][cur_index] = max(dfs(cur_index + 1, count), events[cur_index][2] + dfs(next_index, count - 1))
return dp[count][cur_index]
return dfs(0, k)
1388 - 2023-08-06 17:37:57 +0300 MSK
Number of Music Playlists
Links
Code
class Solution:
def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:
MOD = 10**9 + 7
# Initialize the DP table
dp = [[0 for _ in range(n + 1)] for _ in range(goal + 1)]
dp[0][0] = 1
for i in range(1, goal + 1):
for j in range(1, min(i, n) + 1):
# The i-th song is a new song
dp[i][j] = dp[i - 1][j - 1] * (n - j + 1) % MOD
# The i-th song is a song we have played before
if j > k:
dp[i][j] = (dp[i][j] + dp[i - 1][j] * (j - k)) % MOD
return dp[goal][n]
1389 - 2023-08-06 17:18:41 +0300 MSK
Smallest Sufficient Team
Links
Code
class Solution:
def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:
req_skills_count = len(req_skills)
skill_to_people = defaultdict(set)
for i, person in enumerate(people):
for skill in person:
skill_to_people[skill].add(i)
current = set()
def backtrack(skill: int) -> Tuple[int]:
if skill == req_skills_count:
return tuple(current)
suff_team = None
people_with_skill = skill_to_people[req_skills[skill]]
if current & people_with_skill:
return backtrack(skill + 1)
for person in people_with_skill:
current.add(person)
new_team = backtrack(skill + 1)
current.remove(person)
if suff_team is None or len(new_team) < len(suff_team):
suff_team = new_team
return suff_team
return backtrack(0)
1390 - 2023-08-05 17:53:24 +0300 MSK
Insert Greatest Common Divisors in Linked List
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]:
root = head
while head and head.next:
next = head.next
new_node = ListNode(math.gcd(head.val, head.next.val), next)
head.next = new_node
head = next
return root
1391 - 2023-08-05 17:40:38 +0300 MSK
Account Balance After Rounded Purchase
Links
Code
class Solution:
def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int:
remainder = purchaseAmount % 10
if remainder == 0:
return 100 - purchaseAmount
if remainder >= 5:
return 100 - ((purchaseAmount // 10) + 1) * 10
return 100 - (purchaseAmount // 10) * 10
1392 - 2023-08-05 12:39:41 +0300 MSK
Unique Binary Search Trees II
Links
Code
class Solution:
def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
@cache
def generate_trees(l, r):
return [None] if l > r else [
TreeNode(val, left, right)
for val in range(l, r + 1)
for left in generate_trees(l, val - 1)
for right in generate_trees(val + 1, r)
]
return generate_trees(1, n)
1393 - 2023-08-04 19:40:16 +0300 MSK
Maximum Number of Achievable Transfer Requests
Links
Code
class Solution:
def maximumRequests(self, n, requests):
current = [0] * n
length = len(requests)
def backtrack(req_index: int, count: int) -> int:
if req_index == length:
return 0 if any(current) else count
req_from, req_to = requests[req_index]
current[req_from] -= 1
current[req_to] += 1
take = backtrack(req_index + 1, count + 1)
current[req_from] += 1
current[req_to] -= 1
non_take = backtrack(req_index + 1, count)
return max(take, non_take)
return backtrack(0, 0)
1394 - 2023-08-04 19:38:00 +0300 MSK
Word Break
Links
Code
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
@cache
def calculate(i: int) -> bool:
if i < 0:
return True
for word in wordDict:
length = len(word)
if s[i-length+1:i+1] == word and calculate(i-length):
return True
return False
return calculate(len(s) - 1)
1395 - 2023-08-04 19:37:15 +0300 MSK
Word Break
Links
Code
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
words = set(wordDict)
@cache
def calculate(i: int) -> bool:
if i < 0:
return True
for word in wordDict:
length = len(word)
if s[i-length+1:i+1] == word and calculate(i-length):
return True
return False
return calculate(len(s) - 1)
1396 - 2023-08-03 12:33:31 +0300 MSK
Letter Combinations of a Phone Number
Links
Code
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
length = len(digits)
if length == 0:
return []
digit_map: Dict[int, str] = {
"1": [],
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
"8": ["t", "u", "v"],
"9": ["w", "x", "y", "z"],
"0": [" "]
}
current = []
def backtrack(digit: int) -> Generator[None, None, str]:
if digit == length:
yield "".join(current[:])
return
for char in digit_map[digits[digit]]:
current.append(char)
yield from backtrack(digit + 1)
current.pop()
return tuple(combination for combination in backtrack(0))
1397 - 2023-08-03 12:32:00 +0300 MSK
Letter Combinations of a Phone Number
Links
Code
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
length = len(digits)
if length == 0:
return []
digit_map: Dict[int, str] = {
"1": [],
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
"8": ["t", "u", "v"],
"9": ["w", "x", "y", "z"],
"0": [" "]
}
current = []
def backtrack(digit: int) -> Generator[None, None, str]:
if digit == length:
yield "".join(current[:])
return
for char in digit_map[digits[digit]]:
current.append(char)
yield from backtrack(digit + 1)
current.pop()
return tuple(combination for combination in backtrack(0))
1398 - 2023-08-02 19:02:58 +0300 MSK
Course Schedule
Links
Code
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
courses = defaultdict(set)
for course, prereq in prerequisites:
courses[course].add(prereq)
if not courses:
return True
stack = set()
@cache
def check(course: int) -> bool:
if course not in courses:
return True
if course in stack:
return False
prereqs = courses[course]
if prereqs & stack:
return False
stack.add(course)
for prereq in prereqs:
if not check(prereq):
return False
stack.remove(course)
return True
for course in courses:
if not check(course):
return False
return True
1399 - 2023-08-02 18:11:45 +0300 MSK
Find Eventual Safe States
Links
Code
class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
length = len(graph)
indegree = [0] * length
adj = [[] for _ in range(length)]
for i in range(length):
for edge in graph[i]:
adj[edge].append(i)
indegree[i] += 1
q = deque()
# Push all the nodes with indegree zero in the queue.
for i in range(length):
if indegree[i] == 0:
q.append(i)
safe = [False] * length
while q:
node = q.popleft()
safe[node] = True
for neighbor in adj[node]:
# Delete the edge "node -> neighbor".
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
q.append(neighbor)
safe_nodes = []
for i in range(length):
if safe[i]:
safe_nodes.append(i)
return safe_nodes
1400 - 2023-08-02 17:33:24 +0300 MSK
Maximize the Confusion of an Exam
Links
Code
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
length = len(answerKey)
char_t, char_f = "T", "F"
max_size = k
count = defaultdict(int)
for char in answerKey[:k]:
count[char] += 1
left = 0
for right in range(k, length):
count[answerKey[right]] += 1
while min(count[char_t], count[char_f]) > k:
count[answerKey[left]] -= 1
left += 1
size = right - left + 1
if size > max_size:
max_size = size
return max_size
1401 - 2023-08-02 11:09:23 +0300 MSK
Minimum Size Subarray Sum
Links
Code
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
left = 0
sum_of_subarray = 0
min_length = float('inf')
for right in range(len(nums)):
sum_of_subarray += nums[right]
while sum_of_subarray >= target:
min_length = min(min_length, right - left + 1)
sum_of_subarray -= nums[left]
left += 1
if min_length == float('inf'):
return 0
return min_length
1402 - 2023-08-02 11:07:07 +0300 MSK
Single Number II
Links
Code
class Solution:
def singleNumber(self, nums: List[int]) -> int:
nums.sort()
length = len(nums)
for i in range(0, length, 3):
if i == length - 1:
return nums[i]
num_1, num_2, num_3 = nums[i], nums[i+1], nums[i+2]
if num_1 == num_2 == num_3:
continue
if num_2 == num_3:
return num_1
if num_1 == num_3:
return num_2
return num_3
1403 - 2023-08-02 11:00:07 +0300 MSK
Buddy Strings
Links
Code
class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
length_1, length_2 = len(s), len(goal)
if length_1 != length_2:
return False
if s == goal:
freq = defaultdict(int)
for char in s:
freq[char] += 1
if freq[char] == 2:
return True
return False
swap_1, swap_2 = -1, -1
for i in range(length_1):
char_1, char_2 = s[i], goal[i]
if char_1 == char_2:
continue
if swap_1 == -1:
swap_1 = i
elif swap_2 == -1:
swap_2 = i
else:
return False
return swap_2 != -1 and s[swap_1] == goal[swap_2] and s[swap_2] == goal[swap_1]
1404 - 2023-08-02 10:39:16 +0300 MSK
Generate Parentheses
Links
Code
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
current = []
current_max = n * 2
chars = "()"
def backtrack(open: int, closed: int) -> Generator[None, None, List[str]]:
if len(current) == current_max:
yield "".join(current)
if open:
current.append(chars[0])
yield from backtrack(open - 1, closed)
current.pop()
if closed and closed > open:
current.append(chars[1])
yield from backtrack(open, closed - 1)
current.pop()
return tuple(combination for combination in backtrack(n, n))
1405 - 2023-08-02 10:26:02 +0300 MSK
Permutations
Links
Code
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
length = len(nums)
current = []
current_contains = [False] * length
def backtrack() -> Generator[None, None, List[int]]:
if len(current) == length:
yield tuple(current[:])
return
for i in range(length):
if current_contains[i]:
continue
current_contains[i] = True
current.append(nums[i])
yield from backtrack()
current_contains[i] = False
current.pop()
return
return tuple(combination for combination in backtrack())
1406 - 2023-08-01 20:38:09 +0300 MSK
Maximum Number of Achievable Transfer Requests
Links
Code
class Solution:
def maximumRequests(self, n, requests):
current = [0] * n
length = len(requests)
def backtrack(req_index: int, count: int) -> int:
if req_index == length:
return 0 if any(current) else count
req_from, req_to = requests[req_index]
current[req_from] -= 1
current[req_to] += 1
take = backtrack(req_index + 1, count + 1)
current[req_from] += 1
current[req_to] -= 1
non_take = backtrack(req_index + 1, count)
return max(take, non_take)
return backtrack(0, 0)
1407 - 2023-08-01 20:19:26 +0300 MSK
Maximum Number of Achievable Transfer Requests
Links
Code
class Solution:
def __init__(self):
self.ans = 0
def helper(self, start, requests, indegree, n, count):
if start == len(requests):
for i in range(n):
if indegree[i] != 0:
return
self.ans = max(self.ans, count)
return
# Take
indegree[requests[start][0]] -= 1
indegree[requests[start][1]] += 1
self.helper(start + 1, requests, indegree, n, count + 1)
# Not-take
indegree[requests[start][0]] += 1
indegree[requests[start][1]] -= 1
self.helper(start + 1, requests, indegree, n, count)
def maximumRequests(self, n, requests):
indegree = [0] * n
self.helper(0, requests, indegree, n, 0)
return self.ans
1408 - 2023-08-01 18:39:03 +0300 MSK
Count Complete Subarrays in an Array
Links
Code
class Solution:
def countCompleteSubarrays(self, nums: List[int]) -> int:
length = len(nums)
elems_count = len(set(nums))
if elems_count == length:
return 1
if elems_count == 1:
return length + sum(i for i in range(1, length))
result, elems, min_j = 0, defaultdict(int), 0
for i in range(length):
left = nums[i]
for j in range(min_j, length):
right = nums[j]
elems[right] += 1
if len(elems) != elems_count:
continue
if elems[right] == 1:
elems.pop(right)
else:
elems[right] -= 1
result += length - j
min_j = j
break
else:
return result
if elems[left] == 1:
elems.pop(left)
else:
elems[left] -= 1
return result
1409 - 2023-08-01 17:52:16 +0300 MSK
Number of Employees Who Met the Target
Links
Code
class Solution:
def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
count = 0
for hour in hours:
if hour < target:
continue
count += 1
return count
1410 - 2023-08-01 17:35:47 +0300 MSK
Combinations
Links
Code
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
current = []
def backtrack(first: int) -> Generator[None, None, List[int]]:
if len(current) == k:
yield tuple(current[:])
return
for i in range(first, n + 1):
current.append(i)
yield from backtrack(i + 1)
current.pop()
return
return tuple(combination for combination in backtrack(1))
1411 - 2023-08-01 17:33:23 +0300 MSK
Combinations
Links
Code
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
current, result = [], []
def backtrack(first: int) -> None:
if len(current) == k:
result.append(tuple(current[:]))
return
for i in range(first, n + 1):
current.append(i)
backtrack(i + 1)
current.pop()
return
backtrack(1)
return result
1412 - 2023-08-01 17:14:55 +0300 MSK
Combinations
Links
Code
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
def generate_combinations(elems: List[int], num: int):
total = len(elems)
if num > total:
return
curr_indices = list(range(num))
reversed_num = tuple(reversed(range(num)))
while True:
yield list(elems[i] for i in curr_indices)
for idx in reversed_num:
if curr_indices[idx] != idx + total - num:
break
else:
return
curr_indices[idx] += 1
for j in range(idx+1, num):
curr_indices[j] = curr_indices[j-1] + 1
return [combination for combination in generate_combinations(tuple(range(1, n+1)), k)]
1413 - 2023-07-31 19:28:12 +0300 MSK
Container With Most Water
Links
Code
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
maxArea = 0
while left < right:
currentArea = min(height[left], height[right]) * (right - left)
if currentArea > maxArea:
maxArea = currentArea
if height[left] < height[right]:
left += 1
else:
right -= 1
return maxArea
1414 - 2023-07-31 17:17:46 +0300 MSK
Longest Palindromic Substring
Links
Code
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
dp = [[False] * n for _ in range(n)]
ans = [0, 0]
for i in range(n):
dp[i][i] = True
for i in range(n - 1):
if s[i] == s[i + 1]:
dp[i][i + 1] = True
ans = [i, i + 1]
for diff in range(2, n):
for i in range(n - diff):
j = i + diff
if s[i] == s[j] and dp[i + 1][j - 1]:
dp[i][j] = True
ans = [i, j]
i, j = ans
return s[i:j + 1]
1415 - 2023-07-31 14:46:40 +0300 MSK
Minimum ASCII Delete Sum for Two Strings
Links
Code
class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
length_1, length_2 = len(s1), len(s2)
@cache
def calculate(i: int, j: int) -> int:
if i >= length_1 and j >= length_2:
return 0
if i >= length_1:
return sum(ord(char) for char in s2[j:])
if j >= length_2:
return sum(ord(char) for char in s1[i:])
if s1[i] == s2[j]:
return calculate(i + 1, j + 1)
return min(
ord(s1[i]) + calculate(i + 1, j),
ord(s2[j]) + calculate(i, j + 1)
)
return calculate(0, 0)
1416 - 2023-07-30 20:11:15 +0300 MSK
Strange Printer
Links
Code
class Solution:
def strangePrinter(self, s: str) -> int:
n = len(s)
dp = [[n] * n for _ in range(n)]
for length in range(1, n + 1):
for left in range(n - length + 1):
right = left + length - 1
j = -1
for i in range(left, right):
if s[i] != s[right] and j == -1:
j = i
if j != -1:
dp[left][right] = min(dp[left][right], 1 + dp[j][i] + dp[i + 1][right])
if j == -1:
dp[left][right] = 0
return dp[0][n - 1] + 1
1417 - 2023-07-30 10:12:02 +0300 MSK
Predict the Winner
Links
Code
class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
length = len(nums)
is_even = length % 2 == 0
if length < 3:
return True
@cache
def max_diff(left: int, right: int) -> int:
left_num, right_num = nums[left], nums[right]
if left == right:
return left_num
score_by_left = left_num - max_diff(left + 1, right)
score_by_right = right_num - max_diff(left, right - 1)
return max(score_by_left, score_by_right)
return max_diff(0, length - 1) >= 0
1418 - 2023-07-29 18:54:20 +0300 MSK
Predict the Winner
Links
Code
class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
length = len(nums)
is_even = length % 2 == 0
if length < 3:
return True
@cache
def max_diff(left: int, right: int) -> int:
left_num, right_num = nums[left], nums[right]
if left == right:
return left_num
score_by_left = left_num - max_diff(left + 1, right)
score_by_right = right_num - max_diff(left, right - 1)
return max(score_by_left, score_by_right)
return max_diff(0, length - 1) >= 0
1419 - 2023-07-29 18:51:41 +0300 MSK
Predict the Winner
Links
Code
class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
length = len(nums)
is_even = length % 2 == 0
if length < 3:
return True
def max_diff(left: int, right: int) -> int:
left_num, right_num = nums[left], nums[right]
if left == right:
return left_num
score_by_left = left_num - max_diff(left + 1, right)
score_by_right = right_num - max_diff(left, right - 1)
return max(score_by_left, score_by_right)
return max_diff(0, length - 1) >= 0
1420 - 2023-07-29 13:24:33 +0300 MSK
Soup Servings
Links
Code
class Solution:
def soupServings(self, n: int) -> float:
servings = ceil(n / 25)
states = defaultdict(dict)
moves = [[-4, 0], [-3, -1], [-2, -2], [-1, -3]]
@cache
def calculate(soup_a: int, soup_b: int) -> float:
if soup_a <= 0 and soup_b <= 0:
return 0.5
if soup_a <= 0:
return 1.0
if soup_b <= 0:
return 0.0
if soup_a in states and soup_b in states[soup_a]:
return states[soup_a][soup_b]
state = sum(calculate(soup_a + move[0], soup_b + move[1]) for move in moves) / 4.0
states[soup_a][soup_b] = state
return state
max_probability = 1 - 1e-5
for serving in range(1, servings + 1):
state = calculate(serving, serving)
if state > max_probability:
return 1.0
return calculate(servings, servings)
1421 - 2023-07-27 11:41:11 +0300 MSK
Fair Distribution of Cookies
Links
Code
class Solution:
def distributeCookies(self, cookies: List[int], k: int) -> int:
cur = [0] * k
n = len(cookies)
def dfs(i, zero_count):
# If there are not enough cookies remaining, return `float('inf')`
# as it leads to an invalid distribution.
if n - i < zero_count:
return float('inf')
# After distributing all cookies, return the unfairness of this
# distribution.
if i == n:
return max(cur)
# Try to distribute the i-th cookie to each child, and update answer
# as the minimum unfairness in these distributions.
answer = float('inf')
for j in range(k):
zero_count -= int(cur[j] == 0)
cur[j] += cookies[i]
# Recursively distribute the next cookie.
answer = min(answer, dfs(i + 1, zero_count))
cur[j] -= cookies[i]
zero_count += int(cur[j] == 0)
return answer
return dfs(0, k)
1422 - 2023-07-27 11:39:36 +0300 MSK
Fair Distribution of Cookies
Links
Code
class Solution:
def distributeCookies(self, cookies: List[int], k: int) -> int:
cur = [0] * k
n = len(cookies)
def dfs(i, zero_count):
# If there are not enough cookies remaining, return `float('inf')`
# as it leads to an invalid distribution.
if n - i < zero_count:
return float('inf')
# After distributing all cookies, return the unfairness of this
# distribution.
if i == n:
return max(cur)
# Try to distribute the i-th cookie to each child, and update answer
# as the minimum unfairness in these distributions.
answer = float('inf')
for j in range(k):
zero_count -= int(cur[j] == 0)
cur[j] += cookies[i]
# Recursively distribute the next cookie.
answer = min(answer, dfs(i + 1, zero_count))
cur[j] -= cookies[i]
zero_count += int(cur[j] == 0)
return answer
return dfs(0, k)
1423 - 2023-07-27 11:28:33 +0300 MSK
Maximum Running Time of N Computers
Links
Code
class Solution:
# n = 2, batteries = [3,3,3], Output: 4
# n = 2, batteries = [1,1,1,1], Output: 2
def maxRunTime(self, n: int, batteries: List[int]) -> int:
length = len(batteries)
if length < n:
return 0
if length == n:
return min(batteries)
batteries.sort()
extra = sum(batteries[:-n])
live = batteries[-n:]
# We increase the total running time using 'extra' by increasing
# the running time of the computer with the smallest battery.
for i in range(n - 1):
# If the target running time is between live[i] and live[i + 1].
if extra // (i + 1) < live[i + 1] - live[i]:
return live[i] + extra // (i + 1)
# Reduce 'extra' by the total power used.
extra -= (i + 1) * (live[i + 1] - live[i])
# If there is power left, we can increase the running time
# of all computers.
return live[-1] + extra // n
1424 - 2023-07-26 22:56:56 +0300 MSK
Minimum Speed to Arrive on Time
Links
Code
class Solution:
def minSpeedOnTime(self, dist: List[int], hour: float) -> int:
length = len(dist)
if hour >= sum(dist):
return 1
if hour <= length - 1:
return -1
time_remaining = hour - length + 1
max_speed = int(max(
max(dist), dist[-1] // time_remaining + 1
))
min_speed = 1
result = -1
while min_speed < max_speed:
speed = min_speed + (max_speed - min_speed) // 2
time = dist[-1] / speed + sum(
(distance + speed - 1) // speed
for distance in dist[:-1]
)
if time > hour:
min_speed = speed + 1
else:
max_speed = speed
return min_speed
1425 - 2023-07-25 16:45:40 +0300 MSK
Peak Index in a Mountain Array
Links
Code
class Solution:
# [0,3,2,1,0]
def peakIndexInMountainArray(self, arr: List[int]) -> int:
length = len(arr)
left, right = 0, length - 1
while left < right:
mid = left + (right - left) // 2
if arr[mid] < arr[mid + 1]:
left = mid + 1
else:
right = mid
return left
1426 - 2023-07-25 16:38:25 +0300 MSK
Peak Index in a Mountain Array
Links
Code
class Solution:
# [0,3,2,1,0]
def peakIndexInMountainArray(self, arr: List[int]) -> int:
length = len(arr)
left, right = 0, length - 1
while left <= right:
peak = left + (right - left) // 2
left_val, right_val = arr[peak-1], arr[peak+1]
peak_val = arr[peak]
if left_val < peak_val > right_val:
return peak
if right_val > peak_val:
left = peak + 1
else:
right = peak - 1
return left
1427 - 2023-07-24 21:17:10 +0300 MSK
Longest Substring Without Repeating Characters
Links
Code
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length = len(s)
if length < 2:
return length
max_length, left, charset = 1, 0, set([s[0]])
for right in range(1, length):
letter = s[right]
if letter not in charset:
charset.add(letter)
continue
this_length = right - left
if this_length > max_length:
max_length = this_length
while letter in charset:
charset.remove(s[left])
left += 1
charset.add(letter)
return max(max_length, length - left)
1428 - 2023-07-24 21:04:18 +0300 MSK
Longest Substring Without Repeating Characters
Links
Code
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length = len(s)
if length < 2:
return length
max_length = 0
start = 0
indexes = {s[0]: 0}
for end in range(1, length):
letter = s[end]
if letter not in indexes:
indexes[letter] = end
continue
this_length = end - start
if this_length > max_length:
max_length = this_length
letter_index = indexes[letter]
for remove_letter in s[start:letter_index]:
indexes.pop(remove_letter)
indexes[letter], start = end, letter_index + 1
return max(max_length, length - start)
1429 - 2023-07-24 20:07:58 +0300 MSK
Construct the Rectangle
Links
Code
class Solution:
def constructRectangle(self, area: int) -> List[int]:
return next([area//width, width]
for width in range(int(area**0.5), 0, -1)
if area % width == 0)
1430 - 2023-07-24 19:52:59 +0300 MSK
Max Consecutive Ones
Links
Code
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
max_count, count = 0, 0
for number in nums:
if not number:
max_count = max(max_count, count)
count = 0
continue
count += 1
return max(max_count, count)
1431 - 2023-07-24 19:34:48 +0300 MSK
License Key Formatting
Links
Code
class Solution:
def licenseKeyFormatting(self, s: str, k: int) -> str:
result = []
count = 0
for letter in reversed(s):
if letter == "-":
continue
if count == k:
result.append("-")
count = 0
count += 1
result.append(letter.upper())
return "".join(reversed(result))
1432 - 2023-07-24 19:02:15 +0300 MSK
License Key Formatting
Links
Code
class Solution:
# "5F3Z-2e-9-w" -> "5F3Z2E9W" -> "5F3Z2E9W"
def licenseKeyFormatting(self, s: str, k: int) -> str:
letters = s.replace("-", "").upper()
result = []
end = len(letters)
while end > 0:
start = end - k
if start < 0:
start = 0
result.append(letters[start:end])
end -= k
return "-".join(reversed(result))
1433 - 2023-07-24 18:47:17 +0300 MSK
Island Perimeter
Links
Code
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
perimeter = 0
last_row = len(grid) - 1
last_cell = len(grid[0]) - 1
for i, row in enumerate(grid):
for j, cell in enumerate(row):
if cell == 0:
continue
if j == 0 or row[j-1] == 0:
perimeter += 1
if j == last_cell or row[j+1] == 0:
perimeter += 1
if i == 0 or grid[i-1][j] == 0:
perimeter += 1
if i == last_row or grid[i+1][j] == 0:
perimeter += 1
return perimeter
1434 - 2023-07-24 16:56:56 +0300 MSK
Intersection of Two Arrays
Links
Code
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return set(nums1).intersection(nums2)
1435 - 2023-07-24 16:56:13 +0300 MSK
Intersection of Two Arrays
Links
Code
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return set(nums1) & set(nums2)
1436 - 2023-07-24 16:54:39 +0300 MSK
Find the Difference
Links
Code
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
letters = defaultdict(int)
for letter in s:
letters[letter] += 1
for letter in t:
if letters[letter] == 0:
return letter
letters[letter] -= 1
return None
1437 - 2023-07-24 16:51:33 +0300 MSK
First Unique Character in a String
Links
Code
class Solution:
def firstUniqChar(self, s: str) -> int:
counts = defaultdict(int)
repeated_index = len(s)
for letter in s:
counts[letter] += 1
for i, letter in enumerate(s):
if counts[letter] != 1:
continue
return i
return -1
1438 - 2023-07-24 16:49:38 +0300 MSK
First Unique Character in a String
Links
Code
class Solution:
def firstUniqChar(self, s: str) -> int:
counts = {}
repeated_index = len(s)
for i, letter in enumerate(s):
if letter in counts:
counts[letter] = repeated_index
continue
counts[letter] = i
result = repeated_index
for letter, index in counts.items():
if index == repeated_index:
continue
if index < result:
result = index
return result if result != repeated_index else -1
1439 - 2023-07-24 16:32:14 +0300 MSK
Sum of Left Leaves
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
nodes = set([root])
result = 0
while nodes:
node = nodes.pop()
if node.left and not node.left.left and not node.left.right:
result += node.left.val
elif node.left:
nodes.add(node.left)
if node.right:
nodes.add(node.right)
return result
1440 - 2023-07-24 16:19:40 +0300 MSK
Longest Palindrome
Links
Code
class Solution:
def longestPalindrome(self, s: str) -> int:
counts = defaultdict(int)
for letter in s:
counts[letter] += 1
result = sum(count if count % 2 == 0 else count - 1
for symbol, count in counts.items())
if result < len(s):
result += 1
return result
1441 - 2023-07-24 16:17:10 +0300 MSK
Longest Palindrome
Links
Code
class Solution:
def longestPalindrome(self, s: str) -> int:
counts = defaultdict(int)
for letter in s:
counts[letter] += 1
result = 0
used_odd_letter = False
for letter, count in counts.items():
is_odd = count % 2 != 0
if is_odd and used_odd_letter:
result -= 1
elif is_odd:
used_odd_letter = True
result += count
return result
1442 - 2023-07-24 13:04:29 +0300 MSK
Third Maximum Number
Links
Code
class Solution:
def thirdMax(self, nums: List[int]) -> int:
nums.sort(reverse=True)
number_max = nums[0]
count = 1
for i in range(1, len(nums)):
number = nums[i]
if number == nums[i-1]:
continue
count += 1
if count == 3:
return number
return number_max
1443 - 2023-07-24 13:03:31 +0300 MSK
Third Maximum Number
Links
Code
class Solution:
def thirdMax(self, nums: List[int]) -> int:
nums.sort(reverse=True)
number_max = nums[0]
count = 1
for i in range(1, len(nums)):
number = nums[i]
if number == nums[i-1]:
continue
count += 1
if count == 3:
return number
if number > number_max:
number_max = number
return number_max
1444 - 2023-07-24 12:58:41 +0300 MSK
Add Strings
Links
Code
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
result = []
index_1, index_2 = len(num1) - 1, len(num2) - 1
carry = 0
while index_1 >= 0 or index_2 >= 0 or carry:
digit_1 = num1[index_1] if index_1 >= 0 else 0
digit_2 = num2[index_2] if index_2 >= 0 else 0
digit = int(digit_1) + int(digit_2) + carry
if digit > 9:
carry = 1
digit %= 10
else:
carry = 0
result.append(str(digit))
index_1 -= 1
index_2 -= 1
return "".join(reversed(result))
1445 - 2023-07-24 12:56:22 +0300 MSK
Add Strings
Links
Code
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
result = []
length_1, length_2 = len(num1), len(num2)
index_1, index_2 = length_1 - 1, length_2 - 1
carry = 0
while index_1 >= 0 or index_2 >= 0 or carry:
digit_1 = num1[index_1] if index_1 >= 0 else 0
digit_2 = num2[index_2] if index_2 >= 0 else 0
digit = int(digit_1) + int(digit_2) + carry
if digit > 9:
carry = 1
digit %= 10
else:
carry = 0
result.append(str(digit))
index_1 -= 1
index_2 -= 1
return "".join(reversed(result))
1446 - 2023-07-24 12:44:43 +0300 MSK
Assign Cookies
Links
Code
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort(reverse=True)
s.sort(reverse=True)
count = 0
cookie_index = 0
cookie_count = len(s)
for greed in g:
if cookie_index >= cookie_count or greed > s[cookie_index]:
continue
count += 1
cookie_index += 1
return count
1447 - 2023-07-24 12:40:04 +0300 MSK
Assign Cookies
Links
Code
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
greed = 0
g.sort(reverse=True)
s.sort(reverse=True)
children_count = len(g)
count = 0
for cookie_size in s:
while greed < children_count and g[greed] > cookie_size:
greed += 1
if greed >= children_count:
break
count += 1
greed += 1
return count
1448 - 2023-07-24 11:13:00 +0300 MSK
Pow(x, n)
Links
Code
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n < 0:
n *= -1
x = 1 / x
result = 1
while n:
if n % 2:
result *= x
n -= 1
x *= x
n //= 2
return result
1449 - 2023-07-23 21:12:51 +0300 MSK
Find All Numbers Disappeared in an Array
Links
Code
class Solution:
# [1,1,3,4], [1,2,3,4] -> [2]
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
for number in nums:
index = abs(number) - 1
nums[index] = -1 * abs(nums[index])
return [number
for number in range(1, len(nums) + 1)
if nums[number-1] > 0]
1450 - 2023-07-23 21:01:06 +0300 MSK
Find All Numbers Disappeared in an Array
Links
Code
class Solution:
# [1,1,3,4], [1,2,3,4] -> [2]
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
result = {number: True for number in range(1, len(nums) + 1)}
for number in nums:
result[number] = False
return [number for number, valid in result.items() if valid]
1451 - 2023-07-23 20:55:57 +0300 MSK
Find All Numbers Disappeared in an Array
Links
Code
class Solution:
# [1,1,3,4], [1,2,3,4] -> [2]
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
nums.sort()
result = []
length = len(nums)
j = 0
for i in range(1, length + 1):
while j < length and nums[j] < i:
j += 1
if j < length and nums[j] == i:
continue
result.append(i)
return result
1452 - 2023-07-23 20:18:00 +0300 MSK
Arranging Coins
Links
Code
class Solution:
def arrangeCoins(self, n: int) -> int:
left, right = 0, n
while left <= right:
middle = left + (right - left) // 2
coins = middle * (middle + 1) // 2
if coins == n:
return middle
if coins > n:
right = middle - 1
else:
left = middle + 1
return right
1453 - 2023-07-23 20:03:43 +0300 MSK
Arranging Coins
Links
Code
class Solution:
def arrangeCoins(self, n: int) -> int:
count = 0
row = 1
while n >= row:
n -= row
row += 1
count += 1
return count
1454 - 2023-07-23 19:57:13 +0300 MSK
Middle of the Linked List
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
1455 - 2023-07-23 19:55:42 +0300 MSK
Middle of the Linked List
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
middle = head.next if head else None
tail = middle.next if middle else None
move = True
while tail and tail.next:
tail = tail.next
if move:
middle = middle.next
move = not move
return middle if middle else head
1456 - 2023-07-23 16:50:34 +0300 MSK
All Possible Full Binary Trees
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def allPossibleFBT(self, n: int) -> List[TreeNode]:
if n % 2 == 0:
return []
if n == 1:
return [TreeNode()]
res = []
for i in range(1, n, 2):
left = self.allPossibleFBT(i)
right = self.allPossibleFBT(n - i - 1)
for l in left:
for r in right:
root = TreeNode(0, l, r)
res.append(root)
return res
1457 - 2023-07-22 19:09:00 +0300 MSK
Knight Probability in Chessboard
Links
Code
class Solution:
# y x x
# x x x
# x x x: (2 / 8) * (4 / 16) = 0.0625
# (1/8, 1/8), (2/8, 2/8)
#
# x x x
# x y x
# x x x: 0
def __init__(self):
self.available_moves = (
(2, 1), (1, 2), (-2, 1), (-1, 2), (2, -1), (1, -2),
(-2, -1), (-1, -2)
)
def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
if k < 1:
return 1
if n < 3:
return 0
return self.calculate(row, column, n, k)
@cache
def calculate(self, row: int, column: int, size: int,
moves_left: int) -> float:
if moves_left < 1:
return 1
probability = 0
for row_add, column_add in self.available_moves:
new_row = row_add + row
new_column = column_add + column
if new_row < 0 or new_row >= size or (
new_column < 0 or new_column >= size
):
continue
probability += self.calculate(
new_row, new_column, size, moves_left - 1
) / 8
return probability
1458 - 2023-07-22 17:36:35 +0300 MSK
Knight Probability in Chessboard
Links
Code
class Solution:
def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
# Define possible directions for the knight's moves
directions = [(1, 2), (1, -2), (-1, 2), (-1, -2),
(2, 1), (2, -1), (-2, 1), (-2, -1)]
# Initialize the dynamic programming table
dp = [[[0] * n for _ in range(n)] for _ in range(k + 1)]
dp[0][row][column] = 1
# Iterate over the number of moves
for moves in range(1, k + 1):
# Iterate over the cells on the chessboard
for i in range(n):
for j in range(n):
# Iterate over possible directions
for direction in directions:
prev_i, prev_j = i - direction[0], j - direction[1]
# Check if the previous cell is within the chessboard
if 0 <= prev_i < n and 0 <= prev_j < n:
# Add the previous probability
dp[moves][i][j] += dp[moves - 1][prev_i][prev_j]
# Divide by 8
dp[moves][i][j] /= 8
# Calculate total probability by summing probabilities for all cells
total_probability = sum(
dp[k][i][j]
for i in range(n)
for j in range(n)
)
return total_probability
1459 - 2023-07-21 16:55:34 +0300 MSK
Repeated Substring Pattern
Links
Code
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
length = len(s)
for i in range(1, length // 2 + 1):
if length % i != 0:
continue
if s == s[:i] * (length // i):
return True
return False
1460 - 2023-07-21 16:53:22 +0300 MSK
Repeated Substring Pattern
Links
Code
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
length = len(s)
for i in range(length-1):
if length % (i + 1) != 0:
continue
if s == s[:i+1] * (length // (i + 1)):
return True
return False
1461 - 2023-07-21 16:40:56 +0300 MSK
Add Digits
Links
Code
class Solution:
def addDigits(self, num: int) -> int:
sum = 0
while num > 0:
sum += num % 10
num //= 10
if num == 0 and sum > 9:
num, sum = sum, 0
return sum
1462 - 2023-07-21 16:40:33 +0300 MSK
Add Digits
Links
Code
class Solution:
def addDigits(self, num: int) -> int:
sum = 0
while num > 0:
sum += num % 10
num //= 10
if num == 0 and sum > 9:
num, sum = sum, 0
return sum
1463 - 2023-07-21 16:40:14 +0300 MSK
Add Digits
Links
Code
class Solution:
def addDigits(self, num: int) -> int:
sum = 0
while num > 0:
sum += num % 10
num //= 10
if num == 0 and sum > 9:
num, sum = sum, 0
return sum
1464 - 2023-07-21 16:36:57 +0300 MSK
Add Digits
Links
Code
class Solution:
def addDigits(self, num: int) -> int:
sum = num
while sum > 9:
current_number, current_sum = sum, 0
while current_number:
current_sum += current_number % 10
current_number //= 10
sum = current_sum
return sum
1465 - 2023-07-21 16:30:39 +0300 MSK
Implement Queue using Stacks
Links
Code
class MyQueue:
def __init__(self):
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
self.stack_in.append(x)
def pop(self) -> int:
self.peek()
return self.stack_out.pop()
def peek(self) -> int:
if self.stack_out:
return self.stack_out[-1]
while self.stack_in:
self.stack_out.append(self.stack_in.pop())
return self.stack_out[-1]
def empty(self) -> bool:
return not self.stack_out and not self.stack_in
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
1466 - 2023-07-21 16:20:49 +0300 MSK
Implement Queue using Stacks
Links
Code
class MyQueue:
def __init__(self):
self.queue = []
def push(self, x: int) -> None:
self.queue.insert(0, x)
def pop(self) -> int:
return self.queue.pop()
def peek(self) -> int:
return self.queue[-1]
def empty(self) -> bool:
return len(self.queue) == 0
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
1467 - 2023-07-21 16:09:40 +0300 MSK
Implement Queue using Stacks
Links
Code
class MyQueue:
def __init__(self):
self.queue = deque()
def push(self, x: int) -> None:
self.queue.appendleft(x)
def pop(self) -> int:
return self.queue.pop()
def peek(self) -> int:
return self.queue[-1]
def empty(self) -> bool:
return len(self.queue) == 0
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
1468 - 2023-07-21 16:06:08 +0300 MSK
Power of Two
Links
Code
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 1:
return True
while n > 2 and not n % 2:
n //= 2
return n == 2
1469 - 2023-07-21 15:59:33 +0300 MSK
Remove Duplicates from Sorted List
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
result = head
while head and head.next:
if head.next.val == head.val:
head.next = head.next.next
continue
head = head.next
return result
1470 - 2023-07-21 15:52:55 +0300 MSK
Climbing Stairs
Links
Code
class Solution:
# 1: 1
# 2: 2
# 3: 3 [2(2), 1(1)]
# 4: 5 [3(3), (2)]
def climbStairs(self, n: int) -> int:
if n < 3:
return n
count, count_prev = 2, 1
for number in range(3, n + 1):
count, count_prev = count + count_prev, count
return count
1471 - 2023-07-21 15:33:25 +0300 MSK
Plus One
Links
Code
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
carry = 1
for i in reversed(range(len(digits))):
new_digit = digits[i] + carry
if new_digit > 9:
carry = 1
new_digit %= 10
else:
carry = 0
digits[i] = new_digit
if carry:
digits.insert(0, carry)
return digits
1472 - 2023-07-21 13:34:45 +0300 MSK
Number of Steps to Reduce a Number to Zero
Links
Code
class Solution:
def numberOfSteps(self, num: int) -> int:
count = 0
while num:
count += 1
if num % 2 == 0:
num /= 2
else:
num -= 1
return count
1473 - 2023-07-21 13:33:01 +0300 MSK
Fizz Buzz
Links
Code
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
result = []
for i in range(1, n + 1):
div_by_3, div_by_5 = i % 3 == 0, i % 5 == 0
value = None
if div_by_3 and div_by_5:
value = "FizzBuzz"
elif div_by_3:
value = "Fizz"
elif div_by_5:
value = "Buzz"
else:
value = str(i)
result.append(value)
return result
1474 - 2023-07-21 13:26:34 +0300 MSK
Richest Customer Wealth
Links
Code
class Solution:
def maximumWealth(self, accounts: List[List[int]]) -> int:
max_wealth = 0
for i in range(len(accounts)):
wealth = 0
for j in range(len(accounts[i])):
wealth += accounts[i][j]
if wealth > max_wealth:
max_wealth = wealth
return max_wealth
1475 - 2023-07-21 13:23:06 +0300 MSK
Running Sum of 1d Array
Links
Code
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
for i in range(1, len(nums)):
nums[i] += nums[i-1]
return nums
1476 - 2023-07-21 13:19:55 +0300 MSK
Root Equals Sum of Children
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
return root.val == (root.left.val + root.right.val)
1477 - 2023-07-21 13:18:37 +0300 MSK
Add Two Integers
Links
Code
class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2
1478 - 2023-07-21 13:11:37 +0300 MSK
Number of Longest Increasing Subsequence
Links
Code
class Solution:
def findNumberOfLIS(self, nums: List[int]) -> int:
n = len(nums)
if n <= 1:
return n
lengths = [1] * n
counts = [1] * n
for i in range(1, n):
for j in range(i):
if nums[i] > nums[j]:
if lengths[j] + 1 > lengths[i]:
lengths[i] = lengths[j] + 1
counts[i] = counts[j]
elif lengths[j] + 1 == lengths[i]:
counts[i] += counts[j]
max_length = max(lengths)
return sum(count for length, count in zip(lengths, counts) if length == max_length)
1479 - 2023-07-20 12:12:22 +0300 MSK
Asteroid Collision
Links
Code
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for asteroid in asteroids:
if asteroid > 0:
stack.append(asteroid)
continue
asteroid_abs = abs(asteroid)
while stack and stack[-1] > 0 and stack[-1] < asteroid_abs:
stack.pop()
if stack and stack[-1] == asteroid_abs:
stack.pop()
elif not stack or stack[-1] < 0:
stack.append(asteroid)
return stack
1480 - 2023-07-20 11:41:51 +0300 MSK
Asteroid Collision
Links
Code
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
length = len(asteroids)
if length < 2:
return asteroids
stack = [asteroids[0]]
for i in range(1, length):
asteroid = asteroids[i]
asteroid_last = stack[-1] if stack else 0
stack.append(asteroid)
if asteroid > 0 or (
asteroid < 0 and asteroid_last < 0
):
continue
while len(stack) >= 2 and stack[-1] < 0 and stack[-2] > 0:
last, prev = abs(stack[-1]), abs(stack[-2])
if last == prev:
stack.pop()
elif last > prev:
stack[-1], stack[-2] = stack[-2], stack[-1]
stack.pop()
return stack
1481 - 2023-07-19 14:35:52 +0300 MSK
Best Time to Buy and Sell Stock II
Links
Code
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# It is impossible to sell stock on first day, set -infinity as initial value for cur_hold
cur_hold, cur_not_hold = -float('inf'), 0
for stock_price in prices:
prev_hold, prev_not_hold = cur_hold, cur_not_hold
# either keep hold, or buy in stock today at stock price
cur_hold = max(prev_hold, prev_not_hold - stock_price)
# either keep not-hold, or sell out stock today at stock price
cur_not_hold = max(prev_not_hold,
prev_hold + stock_price)
# maximum profit must be in not-hold state
return cur_not_hold
1482 - 2023-07-19 14:26:39 +0300 MSK
Gas Station
Links
Code
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas) < sum(cost):
return -1
tank, idx = 0, 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
tank, idx = 0, i+1
return idx
1483 - 2023-07-19 14:19:51 +0300 MSK
Jump Game II
Links
Code
class Solution:
def jump(self, nums: List[int]) -> int:
length = len(nums)
result = 0
end = 0
farthest = 0
for i in range(length - 1):
number = nums[i]
max_jump = i + number
if max_jump > farthest:
farthest = max_jump
if farthest >= length - 1:
result += 1
break
if i == end:
result += 1
end = farthest
return result
1484 - 2023-07-19 14:19:26 +0300 MSK
Minimum Size Subarray Sum
Links
Code
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
left = 0
sum_of_subarray = 0
min_length = float('inf')
for right in range(len(nums)):
sum_of_subarray += nums[right]
while sum_of_subarray >= target:
min_length = min(min_length, right - left + 1)
sum_of_subarray -= nums[left]
left += 1
if min_length == float('inf'):
return 0
return min_length
1485 - 2023-07-19 13:39:31 +0300 MSK
H-Index
Links
Code
class Solution:
# [3,0,6,1,5]
# [0,1,3,5,6]
def hIndex(self, citations: List[int]) -> int:
citations = sorted(citations)
length = len(citations)
h = 0
for i in reversed(range(length)):
citations_count = citations[i]
published_count = length - i
if citations_count == 0 or published_count < h:
break
if published_count <= citations_count:
h = published_count
return h
1486 - 2023-07-19 12:33:23 +0300 MSK
Zigzag Conversion
Links
Code
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows < 2:
return s
result: List[List[str]] = [[] for _ in range(numRows)]
row, is_ascending, last = 0, True, numRows - 1
for symbol in s:
result[row].append(symbol)
if is_ascending and row < last:
row += 1
elif is_ascending:
is_ascending = False
if is_ascending:
continue
if row > 0:
row -= 1
else:
is_ascending = True
row = 1
return "".join("".join(row) for row in result)
1487 - 2023-07-19 11:49:03 +0300 MSK
Insert Delete GetRandom O(1)
Links
Code
class RandomizedSet:
def __init__(self):
self._set = set()
self._items = []
self._indexes = {}
def insert(self, val: int) -> bool:
is_in = val in self._set
if not is_in:
self._set.add(val)
self._items.append(val)
self._indexes[val] = len(self._items) - 1
return not is_in
def remove(self, val: int) -> bool:
if val not in self._set:
return False
last = self._items[-1]
val_index = self._indexes[val]
self._items[val_index] = last
self._indexes[last] = val_index
self._set.remove(val)
self._items.pop()
self._indexes.pop(val)
return True
def getRandom(self) -> int:
return random.choice(self._items)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
1488 - 2023-07-19 11:34:17 +0300 MSK
Jump Game
Links
Code
class Solution:
def canJump(self, nums: List[int]) -> bool:
length = len(nums)
if length < 2:
return True
current = nums[0]
for i in range(1, length):
if current == 0:
return False
current -= 1
current = max(current, nums[i])
return True
1489 - 2023-07-19 11:26:05 +0300 MSK
Letter Combinations of a Phone Number
Links
Code
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
length = len(digits)
if length == 0:
return []
digit_map: Dict[int, str] = {
1: [],
2: ["a", "b", "c"],
3: ["d", "e", "f"],
4: ["g", "h", "i"],
5: ["j", "k", "l"],
6: ["m", "n", "o"],
7: ["p", "q", "r", "s"],
8: ["t", "u", "v"],
9: ["w", "x", "y", "z"],
0: [" "]
}
result: List[List[str]] = [
digit_map[int(digit)] for digit in digits
]
return ["".join(i) for i in product(*result)]
1490 - 2023-07-19 11:25:19 +0300 MSK
Letter Combinations of a Phone Number
Links
Code
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
length = len(digits)
if length == 0:
return []
digit_map: Dict[int, str] = {
1: [],
2: ["a", "b", "c"],
3: ["d", "e", "f"],
4: ["g", "h", "i"],
5: ["j", "k", "l"],
6: ["m", "n", "o"],
7: ["p", "q", "r", "s"],
8: ["t", "u", "v"],
9: ["w", "x", "y", "z"],
0: [" "]
}
result: List[List[str]] = [
digit_map[int(digit)] for digit in digits
]
return ["".join(i) for i in product(*result)]
1491 - 2023-07-19 11:14:44 +0300 MSK
Non-overlapping Intervals
Links
Code
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals = sorted(intervals, key=lambda element: element[1])
length = len(intervals)
prev, count = 0, 1
for i in range(1, length):
if intervals[i][0] < intervals[prev][1]:
continue
prev = i
count += 1
return length - count
1492 - 2023-07-18 18:51:03 +0300 MSK
Add Two Numbers
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# create the result pointer that points towards one of the lists
# create the result root pointer that will point towards the root of the result list
# 1. start infinite loop
# 2. if result is false - break, we reached the end
# 3. get values from non-empty pointers
# 4. add values together, store the carry in a variable
# 5. store the value in the result pointer
# 6. move the result pointer to the next node, if there is no next node, use a node from
# another list
# 7. move list pointers
# 8. if we have a carry left, add a node to the result list
def addTwoNumbers(self, l1: Optional[ListNode],
l2: Optional[ListNode]) -> Optional[ListNode]:
carry = 0
result, result_root = l1, l1
while True:
if not l1 and not l2:
break
number_1 = l1.val if l1 else 0
number_2 = l2.val if l2 else 0
result_val = number_1 + number_2 + carry
if result_val > 9:
carry, result_val = 1, result_val - 10
else:
carry = 0
result.val = result_val
if not result.next and l2:
l1 = None
result.next = l2.next
if result.next:
result = result.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if carry:
result.next = ListNode(carry)
return result_root
1493 - 2023-07-18 18:50:17 +0300 MSK
LRU Cache
Links
Code
class LRUCache:
class Node:
def __init__(self, key: str, val: int) -> None:
self.key = key
self.val = val
self.prev: Node = None
self.next: Node = None
def __init__(self, capacity: int) -> None:
self.cap = capacity
self.head = self.Node(-1, -1)
self.tail = self.Node(-1, -1)
self.head.next = self.tail
self.tail.prev = self.head
self.cache = {}
def add_node(self, new_node: Node) -> None:
old_first_node = self.head.next
new_node.next = old_first_node
new_node.prev = self.head
self.head.next = new_node
old_first_node.prev = new_node
def delete_node(self, delete_node: Node) -> None:
prev = delete_node.prev
next = delete_node.next
prev.next = next
next.prev = prev
def get(self, key: int) -> int:
if key not in self.cache:
return -1
result_node = self.cache[key]
result = result_node.val
del self.cache[key]
self.delete_node(result_node)
self.add_node(result_node)
self.cache[key] = self.head.next
return result
def put(self, key: int, value: int) -> None:
if key in self.cache:
current = self.cache[key]
del self.cache[key]
self.delete_node(current)
if len(self.cache) == self.cap:
del self.cache[self.tail.prev.key]
self.delete_node(self.tail.prev)
self.add_node(self.Node(key, value))
self.cache[key] = self.head.next
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
1494 - 2023-07-18 18:39:57 +0300 MSK
LRU Cache
Links
Code
class LRUCache:
class Node:
def __init__(self, key: str, val: int) -> None:
self.key = key
self.val = val
self.prev: Node = None
self.next: Node = None
def __init__(self, capacity: int) -> None:
self.cap = capacity
self.head = self.Node(-1, -1)
self.tail = self.Node(-1, -1)
self.head.next = self.tail
self.tail.prev = self.head
self.cache = {}
def add_node(self, new_node: Node) -> None:
old_first_node = self.head.next
new_node.next = old_first_node
new_node.prev = self.head
self.head.next = new_node
old_first_node.prev = new_node
def delete_node(self, delete_node: Node) -> None:
prev = delete_node.prev
next = delete_node.next
prev.next = next
next.prev = prev
def get(self, key: int) -> int:
if key not in self.cache:
return -1
result_node = self.cache[key]
result = result_node.val
del self.cache[key]
self.delete_node(result_node)
self.add_node(result_node)
self.cache[key] = self.head.next
return result
def put(self, key: int, value: int) -> None:
if key in self.cache:
current = self.cache[key]
del self.cache[key]
self.delete_node(current)
if len(self.cache) == self.cap:
del self.cache[self.tail.prev.key]
self.delete_node(self.tail.prev)
self.add_node(self.Node(key, value))
self.cache[key] = self.head.next
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
1495 - 2023-07-18 18:25:23 +0300 MSK
Search a 2D Matrix
Links
Code
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
length_vertical, length_horizontal = len(matrix), len(matrix[0])
left, right = 0, length_vertical - 1
while left <= right:
mid = left + (right - left) // 2
mid_number = matrix[mid][0]
if mid_number == target:
return True
if mid_number > target:
right = mid - 1
else:
left = mid + 1
vertical_index = right
left, right = 0, length_horizontal - 1
while left <= right:
mid = left + (right - left) // 2
mid_number = matrix[vertical_index][mid]
if mid_number == target:
return True
if mid_number > target:
right = mid - 1
else:
left = mid + 1
return False
1496 - 2023-07-18 18:14:47 +0300 MSK
Search Insert Position
Links
Code
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
length = len(nums)
left, right = 0, length - 1
while left <= right:
mid = left + (right - left) // 2
mid_number = nums[mid]
if mid_number == target:
return mid
if mid_number > target:
right = mid - 1
else:
left = mid + 1
return left
1497 - 2023-07-18 18:10:20 +0300 MSK
Sqrt(x)
Links
Code
class Solution:
def mySqrt(self, x: int) -> int:
if x == 0 or x == 1:
return x
left, right = 1, x
while left <= right:
mid = left + (right - left) // 2
square = mid * mid
if square == x:
return mid
if square > x:
right = mid - 1
else:
left = mid + 1
return right
1498 - 2023-07-18 18:02:32 +0300 MSK
Palindrome Number
Links
Code
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
if x < 10:
return True
number = []
while x:
remainder = x % 10
x = x // 10
number.append(remainder)
length = len(number)
half_index = length // 2
for i, digit in enumerate(number):
last_digit = number[length - i - 1]
if digit != last_digit:
return False
if i != half_index:
continue
return True
1499 - 2023-07-18 18:01:12 +0300 MSK
Palindrome Number
Links
Code
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
if x < 10:
return True
number = []
while x:
remainder = x % 10
x = x // 10
number.append(remainder)
length = len(number)
half_index = length // 2
for i, digit in enumerate(number):
last_digit = number[length - i - 1]
if digit != last_digit:
return False
if i != half_index:
continue
return True
1500 - 2023-07-18 17:58:35 +0300 MSK
Evaluate Reverse Polish Notation
Links
Code
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
operations = {
"+": lambda first, second: first + second,
"-": lambda first, second: first - second,
"*": lambda first, second: first * second,
"/": lambda first, second: int(first / second)
}
for token in tokens:
if token not in operations:
stack.append(int(token))
continue
second, first = stack.pop(), stack.pop()
result = operations[token](first, second)
stack.append(result)
return stack[-1]
1501 - 2023-07-18 17:57:21 +0300 MSK
Add Two Numbers II
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverse(self, head: ListNode) -> ListNode:
previous = None
while head:
next, head.next = head.next, previous
previous, head = head, next
return previous
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
l1, l2 = self.reverse(l1), self.reverse(l2)
head, tail, carry = l1, l1, 0
while l1 or l2 or carry:
val_1 = l1.val if l1 else 0
val_2 = l2.val if l2 else 0
sum = val_1 + val_2 + carry
if sum > 9:
carry = 1
sum %= 10
else:
carry = 0
tail.val = sum
l1, l2 = l1.next if l1 else None, l2.next if l2 else None
if not tail.next and l2:
tail.next = l2
l1 = None
if not tail.next and carry:
tail.next = ListNode(carry)
carry = 0
l2 = None
if tail.next:
tail = tail.next
return self.reverse(head)
1502 - 2023-07-18 17:10:30 +0300 MSK
Reverse Linked List
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
previous = None
while head:
next, head.next = head.next, previous
previous, head = head, next
return previous
1503 - 2023-07-18 16:55:29 +0300 MSK
Two Sum II - Input Array Is Sorted
Links
Code
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
numbers_map: Dict[str, int] = {}
for i, number in enumerate(numbers):
diff = target - number
if diff in numbers_map:
return [numbers_map[diff] + 1, i + 1]
numbers_map[number] = i
return []
1504 - 2023-07-18 16:41:40 +0300 MSK
Reverse Words in a String
Links
Code
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(s.split()[::-1])
1505 - 2023-07-18 16:37:43 +0300 MSK
Integer to Roman
Links
Code
class Solution:
def intToRoman(self, num: int) -> str:
result: List[str] = []
stack: List[int] = deque([
1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000
])
values = {
1000: "M",
900: "CM",
500: "D",
400: "CD",
100: "C",
90: "XC",
50: "L",
40: "XL",
10: "X",
9: "IX",
5: "V",
4: "IV",
1: "I"
}
while num:
roman = stack[-1]
if num < roman:
stack.pop()
continue
result.append(values[roman])
num -= roman
return "".join(result)
1506 - 2023-07-18 16:15:43 +0300 MSK
Evaluate Reverse Polish Notation
Links
Code
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
operations = {
"+": lambda first, second: first + second,
"-": lambda first, second: first - second,
"*": lambda first, second: first * second,
"/": lambda first, second: int(first / second)
}
for token in tokens:
if token not in operations:
stack.append(int(token))
continue
second, first = stack.pop(), stack.pop()
result = operations[token](first, second)
stack.append(result)
return stack[-1]
1507 - 2023-07-18 15:49:17 +0300 MSK
Min Stack
Links
Code
from sortedcontainers import sortedset
class MinStack:
def __init__(self):
self.stack: List[int] = []
self.min_stack: List[int] = []
def push(self, val: int) -> None:
self.stack.append(val)
if not self.min_stack or val <= self.min_stack[-1]:
self.min_stack.append(val)
def pop(self) -> None:
if not self.stack:
return
pop = self.stack.pop()
if pop == self.min_stack[-1]:
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
1508 - 2023-07-18 15:46:05 +0300 MSK
Min Stack
Links
Code
from sortedcontainers import sortedset
class MinStack:
class Node:
def __init__(self, val: int, prev: 'Node'):
self.val = val
self.prev = prev
def __init__(self):
self.stack: List[Node] = []
self.min_node = None
def push(self, val: int) -> None:
new_node = self.Node(val, None)
self.stack.append(new_node)
if self.min_node is None or val <= self.min_node.val:
new_node.prev = self.min_node
self.min_node = new_node
def pop(self) -> None:
pop = self.stack.pop()
if pop == self.min_node:
self.min_node = self.min_node.prev
def top(self) -> int:
return self.stack[-1].val
def getMin(self) -> int:
return self.min_node.val
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
1509 - 2023-07-18 15:23:22 +0300 MSK
Simplify Path
Links
Code
class Solution:
def simplifyPath(self, path: str) -> str:
canonical = []
for directory in path.split("/"):
if not directory or directory == ".":
continue
if directory != "..":
canonical.append(directory)
continue
if len(canonical):
canonical.pop()
return "/" + "/".join(canonical)
1510 - 2023-07-18 15:15:34 +0300 MSK
Longest Consecutive Sequence
Links
Code
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
length = len(nums)
if length < 2:
return length
nums = set(nums)
longest = 1
for number in nums:
if number - 1 in nums:
continue
consequent = 1
while number + consequent in nums:
consequent += 1
longest = max(longest, consequent)
return longest
1511 - 2023-07-18 15:08:44 +0300 MSK
Longest Consecutive Sequence
Links
Code
from sortedcontainers import SortedSet
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums = SortedSet(nums)
longest, current = 0, 0
for number in nums:
if number - 1 in nums:
current += 1
continue
if current > longest:
longest = current
current = 1
return max(current, longest)
1512 - 2023-07-18 14:53:17 +0300 MSK
Group Anagrams
Links
Code
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams: Dict[str, List[str]] = defaultdict(list)
for string in strs:
anagrams["".join(sorted(string))].append(string)
return anagrams.values()
1513 - 2023-07-18 14:46:38 +0300 MSK
LRU Cache
Links
Code
class LRUCache:
class Node:
def __init__(self, key: str, val: int) -> None:
self.key = key
self.val = val
self.prev: Node = None
self.next: Node = None
def __init__(self, capacity: int) -> None:
self.cap = capacity
self.head = self.Node(-1, -1)
self.tail = self.Node(-1, -1)
self.head.next = self.tail
self.tail.prev = self.head
self.cache = {}
def add_node(self, new_node: Node) -> None:
old_first_node = self.head.next
new_node.next = old_first_node
new_node.prev = self.head
self.head.next = new_node
old_first_node.prev = new_node
def delete_node(self, delete_node: Node) -> None:
prev = delete_node.prev
next = delete_node.next
prev.next = next
next.prev = prev
def get(self, key: int) -> int:
if key not in self.cache:
return -1
result_node = self.cache[key]
result = result_node.val
del self.cache[key]
self.delete_node(result_node)
self.add_node(result_node)
self.cache[key] = self.head.next
return result
def put(self, key: int, value: int) -> None:
if key in self.cache:
current = self.cache[key]
del self.cache[key]
self.delete_node(current)
if len(self.cache) == self.cap:
del self.cache[self.tail.prev.key]
self.delete_node(self.tail.prev)
self.add_node(self.Node(key, value))
self.cache[key] = self.head.next
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
1514 - 2023-07-18 13:48:20 +0300 MSK
Rotate Array
Links
Code
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
k %= length
nums[length - k:] = nums[length - k:][::-1]
nums[:length - k] = nums[:length - k][::-1]
nums[:] = nums[::-1]
1515 - 2023-07-16 19:26:31 +0300 MSK
Remove Duplicates from Sorted Array II
Links
Code
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = len(nums)
if length < 2:
return length
current_index = 2
for number in nums[2:]:
if number == nums[current_index-2]:
continue
nums[current_index] = number
current_index += 1
return current_index
1516 - 2023-07-16 19:19:33 +0300 MSK
Remove Duplicates from Sorted Array II
Links
Code
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = len(nums)
if length < 2:
return length
current_number, unique, current_index = nums[0], True, 1
for number in nums[1:]:
if current_number != number:
current_number = number
unique = True
nums[current_index] = number
current_index += 1
continue
if unique:
nums[current_index] = number
current_index += 1
unique = False
return current_index
1517 - 2023-07-16 18:35:46 +0300 MSK
Same Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p and not q or (q and not p):
return False
if not p and not q:
return True
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
1518 - 2023-07-16 15:06:38 +0300 MSK
Maximum Depth of Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode], depth: int = 0) -> int:
if not root:
return depth
return max(self.maxDepth(root.left, depth + 1), self.maxDepth(root.right, depth + 1))
1519 - 2023-07-16 15:04:36 +0300 MSK
Maximum Depth of Binary Tree
Links
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode], count: int = 0) -> int:
if not root:
return 0
if not root.left and not root.right:
return count + 1
return max(self.maxDepth(root.left, count + 1), self.maxDepth(root.right, count + 1))
1520 - 2023-07-16 13:34:50 +0300 MSK
Merge Two Sorted Lists
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1:
return list2
if not list2:
return list1
head = None
if list1.val < list2.val:
head, list1 = list1, list1.next
else:
head, list2 = list2, list2.next
current = head
while list1 and list2:
if list1.val < list2.val:
current.next, list1 = list1, list1.next
else:
current.next, list2 = list2, list2.next
current = current.next
if list1 or list2:
current.next = list1 if list1 else list2
return head
1521 - 2023-07-16 12:53:42 +0300 MSK
Linked List Cycle
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow_p, fast_p = head, head.next if head else None
while fast_p and fast_p.next:
if slow_p == fast_p:
return True
slow_p, fast_p = slow_p.next, fast_p.next.next
return False
1522 - 2023-07-16 12:51:01 +0300 MSK
Linked List Cycle
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow_p, fast_p = head, head.next if head else None
while slow_p and fast_p:
if slow_p == fast_p:
return True
slow_p = slow_p.next
fast_p = fast_p.next if fast_p else None
fast_p = fast_p.next if fast_p else None
return False
1523 - 2023-07-16 12:38:36 +0300 MSK
Valid Parentheses
Links
Code
class Solution:
def isValid(self, s: str) -> bool:
length = len(s)
if length < 2:
return False
brackets_open = {
"{": "}",
"(": ")",
"[": "]"
}
brackets_close = brackets_open.values()
stack = [s[0]]
for bracket in s[1:]:
if bracket not in brackets_close:
stack.append(bracket)
continue
if len(stack) == 0 or brackets_open.get(stack[-1]) != bracket:
return False
stack.pop()
return not len(stack)
1524 - 2023-07-16 12:17:02 +0300 MSK
Contains Duplicate II
Links
Code
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
indexes = {}
for i, number in enumerate(nums):
if number in indexes and abs(i - indexes[number]) <= k:
return True
indexes[number] = i
return False
1525 - 2023-07-16 12:16:10 +0300 MSK
Contains Duplicate II
Links
Code
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
indexes = defaultdict(set)
for i, number in enumerate(nums):
if number in indexes and any(abs(i - j) <= k for j in indexes[number]):
return True
indexes[number].add(i)
return False
1526 - 2023-07-16 10:47:21 +0300 MSK
Happy Number
Links
Code
class Solution:
def isHappy(self, n: int) -> bool:
sums = set()
while n != 1:
if n in sums:
return False
sums.add(n)
sum = 0
while n > 0:
sum += (n % 10 )**2
n = n // 10
n = sum
return True
1527 - 2023-07-16 10:41:43 +0300 MSK
Happy Number
Links
Code
class Solution:
def isHappy(self, n: int) -> bool:
while True:
sum = 0
while n > 0:
sum += (n % 10 )**2
n = n // 10
n = sum
if sum < 10:
break
return n in [1, 7]
1528 - 2023-07-16 10:41:26 +0300 MSK
Happy Number
Links
Code
class Solution:
def isHappy(self, n: int) -> bool:
while True:
sum = 0
while n > 0:
sum += (n % 10 )**2
n = n // 10
n = sum
print(n)
if sum < 10:
break
return n in [1, 7]
1529 - 2023-07-15 21:24:48 +0300 MSK
Two Sum
Links
Code
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
indexes = {}
for i, number in enumerate(nums):
diff = target - number
if diff in indexes:
return [indexes[diff], i]
indexes[number] = i
1530 - 2023-07-15 21:22:16 +0300 MSK
Valid Anagram
Links
Code
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s_length, t_length = len(s), len(t)
if s_length != t_length:
return False
count = defaultdict(int)
for i, s_symbol in enumerate(s):
t_symbol = t[i]
count[s_symbol] += 1
count[t_symbol] -= 1
return not any((i != 0 for i in count.values()))
1531 - 2023-07-15 21:11:36 +0300 MSK
Word Pattern
Links
Code
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
words_length, pattern_length = len(words), len(pattern)
if words_length != pattern_length:
return False
symbol_to_word = {}
word_to_symbol = {}
for i, symbol in enumerate(pattern):
word = words[i]
symbol_in, word_in = symbol in symbol_to_word, word in word_to_symbol
if symbol_in and word_in and symbol_to_word[symbol] == word:
continue
if not symbol_in and not word_in:
symbol_to_word[symbol] = word
word_to_symbol[word] = symbol
continue
return False
return True
1532 - 2023-07-15 20:53:31 +0300 MSK
Isomorphic Strings
Links
Code
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
s_length, t_length = len(s), len(t)
if s_length != t_length:
return False
s_to_t = {}
t_to_s = {}
for i, s_symbol in enumerate(s):
t_symbol = t[i]
if s_symbol not in s_to_t and t_symbol not in t_to_s:
s_to_t[s_symbol] = t_symbol
t_to_s[t_symbol] = s_symbol
elif s_symbol in s_to_t and s_to_t[s_symbol] == t_symbol:
continue
else:
return False
return True
1533 - 2023-07-15 20:49:31 +0300 MSK
Isomorphic Strings
Links
Code
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
return list(map(s.index, s)) == list(map(t.index, t))
1534 - 2023-07-15 20:05:44 +0300 MSK
Ransom Note
Links
Code
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ransom_i, magazine_i = 0, 0
ransom_length, magazine_length = len(ransomNote), len(magazine)
if magazine_length < ransom_length:
return False
if ransom_length == 1:
return ransomNote in magazine
symbols = [0 for _ in range(26)]
for symbol in magazine:
symbols[ord(symbol)-97] += 1
for symbol in ransomNote:
symbols[ord(symbol)-97] -= 1
return not any((count < 0 for count in symbols))
1535 - 2023-07-15 19:55:32 +0300 MSK
Ransom Note
Links
Code
class Solution:
# two indexes: ransom_i, magazine_i
# sort both ransomNote and magazine (ascending order)
# while indexes have not reached the end:
# - if ransom symbol is equal to the magazine_symbol: increase both indexes
# - if it is not equal, increase only magazine index
# return wheter the ranson index is equal to the length of the ransom
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ransom_i, magazine_i = 0, 0
ransom_length, magazine_length = len(ransomNote), len(magazine)
if magazine_length < ransom_length:
return False
if ransom_length == 1:
return ransomNote in magazine
ransomNote = sorted(ransomNote)
magazine = sorted(magazine)
while ransom_i < ransom_length and magazine_i < magazine_length:
ransom_symbol, magazine_symbol = ransomNote[ransom_i], magazine[magazine_i]
if magazine_symbol > ransom_symbol:
return False
if ransom_symbol == magazine_symbol:
ransom_i += 1
magazine_i += 1
return ransom_i == ransom_length
1536 - 2023-07-15 19:35:16 +0300 MSK
Ransom Note
Links
Code
class Solution:
# two indexes: ransom_i, magazine_i
# sort both ransomNote and magazine (ascending order)
# while indexes have not reached the end:
# - if ransom symbol is equal to the magazine_symbol: increase both indexes
# - if it is not equal, increase only magazine index
# return wheter the ranson index is equal to the length of the ransom
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ransom_i, magazine_i = 0, 0
ransom_length, magazine_length = len(ransomNote), len(magazine)
ransomNote = sorted(ransomNote)
magazine = sorted(magazine)
if magazine_length < ransom_length:
return False
while ransom_i < ransom_length and magazine_i < magazine_length:
ransom_symbol, magazine_symbol = ransomNote[ransom_i], magazine[magazine_i]
if ransom_symbol == magazine_symbol:
ransom_i += 1
magazine_i += 1
return ransom_i == ransom_length
1537 - 2023-07-13 21:11:33 +0300 MSK
Is Subsequence
Links
Code
class Solution:
# create two pointers, original and sub, both are zero
# while either of those pointers have not reached the end:
# - if original symbol is equal to the sub, move both pointer to the right
# - if not, move original pointer to the right
# if sub pointer reached the end, return True, otherwise False
def isSubsequence(self, s: str, t: str) -> bool:
original, sub = 0, 0
original_length, sub_length = len(t), len(s)
while original < original_length and sub < sub_length:
if s[sub] == t[original]:
original += 1
sub += 1
continue
original += 1
return sub == sub_length
1538 - 2023-07-13 20:57:51 +0300 MSK
Longest Common Prefix
Links
Code
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 1:
return strs[0]
min_length = min([len(string) for string in strs])
prefix = strs[0][0:min_length]
for string in strs:
if not prefix:
return ""
while not string.startswith(prefix):
prefix = prefix[0:-1]
return prefix
1539 - 2023-07-13 20:49:03 +0300 MSK
Longest Common Prefix
Links
Code
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 1:
return strs[0]
min_length = min([len(string) for string in strs])
for i in range(min_length, -1, -1):
current = strs[0][0:i+1]
for string in strs[1:]:
if string[0:i+1] != current:
break
else:
return current
return ""
1540 - 2023-07-13 20:34:54 +0300 MSK
Roman to Integer
Links
Code
class Solution:
def romanToInt(self, input_numbers: str) -> int:
result = 0
previous = None
values = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
subtractions = set(["IV", "IX", "XL", "XC", "CD", "CM"])
for number in input_numbers:
if f"{previous}{number}" in subtractions:
result += values[number] - values[previous] * 2
else:
result += values[number]
previous = number
return result
1541 - 2023-07-13 20:32:03 +0300 MSK
Majority Element
Links
Code
class Solution:
def majorityElement(self, nums: List[int]) -> int:
return sorted(nums)[len(nums)//2]
1542 - 2023-07-13 20:30:18 +0300 MSK
Best Time to Buy and Sell Stock
Links
Code
class Solution:
# Input: prices = [7,1,5,3,6,4]
# Output: 5
# Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
# Note that buying on day 2 and selling on day 1 is not allowed because you must buy
# before you sell.
def maxProfit(self, prices: List[int]) -> int:
length = len(prices)
if length < 2:
return 0
left, right, profit = 0, 1, 0
while right < length:
current_profit = prices[right] - prices[left]
is_profitable = current_profit > 0
if is_profitable and current_profit > profit:
profit = current_profit
elif not is_profitable:
left = right
right += 1
return profit
1543 - 2023-07-13 20:19:45 +0300 MSK
Best Time to Buy and Sell Stock
Links
Code
class Solution:
# Input: prices = [7,1,5,3,6,4]
# Output: 5
# Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
# Note that buying on day 2 and selling on day 1 is not allowed because you must buy
# before you sell.
def maxProfit(self, prices: List[int]) -> int:
length = len(prices)
if length < 2:
return 0
left, right, profit = 0, 1, 0
while right < length:
current_profit = prices[right] - prices[left]
if current_profit > 0:
profit = max(current_profit, profit)
else:
left = right
right += 1
return profit
1544 - 2023-07-13 19:37:36 +0300 MSK
Majority Element
Links
Code
class Solution:
def majorityElement(self, nums: List[int]) -> int:
return sorted(nums)[len(nums)//2]
1545 - 2023-07-13 19:13:31 +0300 MSK
Remove Duplicates from Sorted Array
Links
Code
class Solution:
# non-decreasing order, so to remove the duplicates we just need to remove all
# consequent duplicates
# create replace index, set it to 1 - the first element is always unique
# check if length is more than 1 to avoid out-of-bounds -
# if the length is one, just return 1
# iterate over nums starting from the second element:
# - if the current number is not equal to the previous,
# set nums[replace] to it, move the replace index
# - if the current number is equal to the previous one, continue
# return replace
def removeDuplicates(self, nums: List[int]) -> int:
replace = 1
for i, number in enumerate(nums[1:], 1):
if number == nums[i-1]:
continue
nums[replace] = number
replace += 1
return replace
1546 - 2023-07-13 19:03:15 +0300 MSK
Remove Duplicates from Sorted Array
Links
Code
class Solution:
# non-decreasing order, so to remove the duplicates we just need to remove all
# consequent duplicates
# create replace index, set it to 0
# create a set of duplicates
# iterate over nums:
# - if the number is in the set, continue
# - if the number is not in the set, set nums[replace] to that number, add it to the set
# return replace
def removeDuplicates(self, nums: List[int]) -> int:
replace, duplicates = 0, set()
for i, number in enumerate(nums):
if number in duplicates:
continue
nums[replace] = number
replace += 1
duplicates.add(number)
return replace
1547 - 2023-07-13 18:52:44 +0300 MSK
Remove Element
Links
Code
class Solution:
# create replace index
# iterate over nums:
# - if the current number is equal to val, continue
# - set nums[replace] to that number, increase the index
def removeElement(self, nums: List[int], val: int) -> int:
replace = 0
for i, number in enumerate(nums):
if number == val:
continue
nums[replace] = number
replace += 1
return replace
1548 - 2023-07-13 18:46:43 +0300 MSK
Remove Element
Links
Code
class Solution:
# create two indexes, current and replace
# create non_val_count
# while to-be-replaced has not reached the end:
# - if the current number is a regular number, move the current index,
# increase non_val_count
# - if the replace index is equal or less than the current, move it and continue
# - if the replace number is a non-regular number, move the replace index and continue
# - if the current number is a non-regular, replace it with the replace number,
# replace the replace number with val, move both indexes
# return the current index + 1
def removeElement(self, nums: List[int], val: int) -> int:
current, replace, val_count, length = 0, 0, 0, len(nums)
non_val_count = 0
while replace < length and current < length:
current_number, replace_number = nums[current], nums[replace]
if current_number != val:
current += 1
non_val_count += 1
continue
if replace <= current:
replace = current + 1
continue
if replace_number == val:
replace += 1
continue
nums[current], nums[replace] = replace_number, val
replace += 1
current += 1
non_val_count += 1
return non_val_count
1549 - 2023-07-12 20:34:00 +0300 MSK
Merge Sorted Array
Links
Code
class Solution:
# have three indexes: nums1 (end of array 1), nums2 (from the end),
# and current (nums1 from the end)
# if nums2 number is bigger or equal than nums1 number, put the number at the current index,
# move both indexes
# if nums1 number is smaller than nums2 number, put the number at the current index,
# move both indexes
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
nums1_i, nums2_i = m - 1, n - 1
for i in range(m + n - 1, -1, -1):
nums1_number = nums1[nums1_i] if nums1_i >= 0 else nums2[0] - 1
nums2_number = nums2[nums2_i] if nums2_i >= 0 else nums1[0] - 1
if nums1_number >= nums2_number:
nums1[i] = nums1_number
nums1_i -= 1
continue
nums1[i] = nums2_number
nums2_i -= 1
1550 - 2023-07-11 17:42:28 +0300 MSK
Valid Palindrome
Links
Code
class Solution:
def isPalindrome(self, s: str) -> bool:
length = len(s)
# if the sring has only one symbol and it is alphanumeric, it is a palyndrom
if s.isalnum() and length == 1:
return True
i, j = 0, length - 1
# iterate from the start and from the end using two indexes:
# - if one the symbols is not alphanumeric, move the corresponding index
# - if symbols are alphanumeric and not equal, return False
# - move indexes
while i < j:
symbol_start, symbol_end = s[i].lower(), s[j].lower()
if not symbol_start.isalnum():
i += 1
continue
if not symbol_end.isalnum():
j -= 1
continue
if symbol_start != symbol_end:
return False
i += 1
j -= 1
return True
1551 - 2023-07-11 17:40:20 +0300 MSK
Valid Palindrome
Links
Code
class Solution:
def isPalindrome(self, s: str) -> bool:
length = len(s)
# if the sring has only one symbol and it is alphanumeric, it is a palyndrom
if s.isalnum() and length == 1:
return True
i, j = 0, length - 1
# iterate from start and from end:
# - if the symbol is not alphanumeric, skip
# - if the symbol is alphanumeric, compare
# - if indexes are equal or reversed, return
while i < j:
symbol_start, symbol_end = s[i].lower(), s[j].lower()
if not symbol_start.isalnum():
i += 1
continue
if not symbol_end.isalnum():
j -= 1
continue
if symbol_start != symbol_end:
return False
i += 1
j -= 1
return True
1552 - 2023-07-10 15:59:08 +0300 MSK
Find the Index of the First Occurrence in a String
Links
Code
class Solution:
# check edge cases:
# - if length of the needle is less than the length of the haystack: -1
# - if strings are equal: 0
# - if length of the needle is equal to the length of the haystack, but
# strings are not equal: -1
# iterate over haystack and needle cheking if a substring starting with the current symbol
# is equal to the needle
def strStr(self, haystack: str, needle: str) -> int:
length_needle, length_haystack = len(needle), len(haystack)
last_needle_index = length_needle - 1
if length_needle > length_haystack:
return -1
if haystack == needle:
return 0
if length_needle == length_haystack:
return -1
if needle == haystack:
return 0
for i, _ in enumerate(haystack):
current_needle = haystack[i:i+length_needle]
if current_needle == needle:
return i
return -1
1553 - 2023-07-10 15:57:30 +0300 MSK
Find the Index of the First Occurrence in a String
Links
Code
class Solution:
# check edge cases:
# - if length of the needle is less than the length of the haystack: -1
# - if strings are equal: 0
# - if length of the needle is equal to the length of the haystack, but
# strings are not equal: -1
# iterate over haystack and needle cheking if a symbol from haystack
# corresponds to the symbol in needle
def strStr(self, haystack: str, needle: str) -> int:
length_needle, length_haystack = len(needle), len(haystack)
last_needle_index = length_needle - 1
if length_needle > length_haystack:
return -1
if haystack == needle:
return 0
if length_needle == length_haystack:
return -1
if needle == haystack:
return 0
j = length_needle
for i, _ in enumerate(haystack):
current_needle = haystack[i:j]
if current_needle == needle:
return i
j += 1
return -1
1554 - 2023-07-10 15:49:18 +0300 MSK
Find the Index of the First Occurrence in a String
Links
Code
class Solution:
# check edge cases:
# - if length of the needle is less than the length of the haystack: -1
# - if strings are equal: 0
# - if length of the needle is equal to the length of the haystack, but
# strings are not equal: -1
# iterate over haystack and needle cheking if a symbol from haystack
# corresponds to the symbol in needle
def strStr(self, haystack: str, needle: str) -> int:
length_needle, length_haystack = len(needle), len(haystack)
last_needle_index = length_needle - 1
if length_needle > length_haystack:
return -1
if haystack == needle:
return 0
if length_needle == length_haystack:
return -1
if needle == haystack:
return 0
i, j = 0, length_needle
while j <= len(haystack):
current_needle = haystack[i:j]
if current_needle == needle:
return i
i += 1
j += 1
return -1
1555 - 2023-07-08 18:57:18 +0300 MSK
Length of Last Word
Links
Code
class Solution:
# we need to iterate over the string searching for words
# add a whitespace to the end to avoid the situation when the last symbol is non-whitespace
# possible combinations:
# 1. a whitespace after a symbol: end of the word
# 2. a whitespace after a whitespace: ignore
# 3. a symbol after a symbol: ignore
def lengthOfLastWord(self, s: str) -> int:
s += " "
result, word_length = 0, 0
for i, symbol in enumerate(s):
if symbol != " ":
word_length += 1
continue
if word_length > 0:
result = word_length
word_length = 0
return result
1556 - 2023-07-08 18:48:01 +0300 MSK
Length of Last Word
Links
Code
class Solution:
# we need to iterate over the string searching for words
# possible combinations:
# 1. a whitespace after a symbol: end of the word
# 2. a whitespace after a whitespace: ignore
# 3. a symbol after a symbol, but it's the last symbol: end of the last word
# 4. a symbol after a symbol: ignore
def lengthOfLastWord(self, s: str) -> int:
length = len(s)
if length == 1:
return 1
word_start, word_end, in_word = 0, 0, False
for i, symbol in enumerate(s):
is_whitespace = symbol == " "
is_last = i == length - 1
if is_whitespace and in_word:
in_word = False
word_end = i - 1
continue
if is_whitespace and not in_word:
continue
if not is_whitespace and in_word and is_last:
word_end = i
continue
if not is_whitespace and not in_word and is_last:
word_end = i
word_start = i
continue
if not is_whitespace and in_word:
continue
if not is_whitespace and not in_word:
word_start = i
in_word = True
continue
return word_end - word_start + 1
1557 - 2023-07-08 18:25:39 +0300 MSK
Length of Last Word
Links
Code
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.split()[-1])
1558 - 2023-07-06 20:44:21 +0300 MSK
Add Two Numbers
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# create the result pointer that points towards one of the lists
# create the result root pointer that will point towards the root of the result list
# 1. start infinite loop
# 2. if result is false - break, we reached the end
# 3. get values from non-empty pointers
# 4. add values together, store the carry in a variable
# 5. store the value in the result pointer
# 6. move the result pointer to the next node, if there is no next node, use a node from
# another list
# 7. move list pointers
# 8. if we have a carry left, add a node to the result list
def addTwoNumbers(self, l1: Optional[ListNode],
l2: Optional[ListNode]) -> Optional[ListNode]:
carry = 0
result, result_root = l1, l1
while True:
if not l1 and not l2:
break
number_1 = l1.val if l1 else 0
number_2 = l2.val if l2 else 0
result_val = number_1 + number_2 + carry
if result_val > 9:
carry, result_val = 1, result_val - 10
else:
carry = 0
result.val = result_val
if not result.next and l2:
l1 = None
result.next = l2.next
if result.next:
result = result.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if carry:
result.next = ListNode(carry)
return result_root
1559 - 2023-07-06 15:43:40 +0300 MSK
Roman to Integer
Links
Code
class Solution:
def romanToInt(self, input_numbers: str) -> int:
result = 0
previous = None
values = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
subtractions = set(["IV", "IX", "XL", "XC", "CD", "CM"])
for number in input_numbers:
if f"{previous}{number}" in subtractions:
result = result - values[previous] * 2 + values[number]
else:
result += values[number]
previous = number
return result
1560 - 2023-05-24 13:25:03 +0300 MSK
Remove Element
Links
Code
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
length = len(nums)
if not length:
return 0
first = nums[0]
if length == 1 and first == val:
nums.pop()
return 0
if length == 1 and first != val:
return 1
not_equal_index = -1 if first == val else 0
for i, number in enumerate(nums[1:], 1):
if number == val:
continue
not_equal_index += 1
nums[not_equal_index] = number
return not_equal_index + 1
1561 - 2023-05-24 13:11:40 +0300 MSK
Remove Duplicates from Sorted Array
Links
Code
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = len(nums)
if length == 1:
return 1
unique_count = 1
last_unique_index = 0
for i, number in enumerate(nums[1:], 1):
last_unique = nums[last_unique_index]
if number == last_unique:
continue
unique_count += 1
last_unique_index += 1
nums[last_unique_index] = number
nums = nums[:last_unique_index+1]
return unique_count
1562 - 2023-05-24 12:54:30 +0300 MSK
Merge Two Sorted Lists
Links
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
result = ListNode()
current = result
while list1 and list2:
if list1.val < list2.val:
current.next = list1
list1, current = list1.next, list1
continue
current.next = list2
list2, current = list2.next, list2
if list1 or list2:
current.next = list1 if list1 else list2
return result.next
1563 - 2023-05-24 12:13:29 +0300 MSK
Valid Parentheses
Links
Code
class Solution:
def isValid(self, s: str) -> bool:
brackets = []
symbols = {
"{": "}",
"(": ")",
"[": "]"
}
open = symbols.keys()
closed = symbols.values()
for bracket in s:
if bracket in open:
brackets.append(bracket)
continue
if not brackets:
return False
last_bracket = brackets[-1]
if last_bracket in closed:
return False
correct_closing_bracket = symbols[last_bracket]
if bracket != correct_closing_bracket:
return False
brackets.pop()
return not len(brackets)
1564 - 2023-05-24 11:52:15 +0300 MSK
Palindrome Number
Links
Code
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
if x < 10:
return True
number = []
while True:
remainder = x % 10
x = int(x / 10)
number.append(remainder)
if not x:
break
number.reverse()
print(number)
length = len(number)
half_index = int(length / 2)
for i, digit in enumerate(number):
last_digit = number[length - i - 1]
if digit != last_digit:
return False
if i != half_index:
continue
return True
1565 - 2023-05-24 11:37:01 +0300 MSK
Longest Common Prefix
Links
Code
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
answer = []
strings = sorted(strs)
first = strings[0]
last = strings[-1]
min_length = min(len(first), len(last))
for i in range(min_length):
first_symbol = first[i]
last_symbol = last[i]
if first_symbol == last_symbol:
answer.append(first_symbol)
continue
return "".join(answer)
return "".join(answer)
1566 - 2023-05-24 11:26:20 +0300 MSK
Roman to Integer
Links
Code
class Solution:
def romanToInt(self, s: str) -> int:
result = 0
skip = False
values = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
special_cases = {
"I": ["V", "X"],
"X": ["L", "C"],
"C": ["D", "M"]
}
for i, symbol in enumerate(s):
if skip:
skip = False
continue
next = None
if i < (len(s) - 1):
next = s[i+1]
if next in special_cases.get(symbol, []):
skip = True
result += values[next] - values[symbol]
continue
result += values[symbol]
return result
1567 - 2023-05-24 11:15:01 +0300 MSK
Roman to Integer
Links
Code
class Solution:
def romanToInt(self, s: str) -> int:
result = 0
skip = False
for i, symbol in enumerate(s):
if skip:
skip = False
continue
next = ""
if i < len(s) - 1:
next = s[i+1]
if symbol == "I" and next == "V":
result += 4
skip = True
continue
if symbol == "I" and next == "X":
result += 9
skip = True
continue
if symbol == "I":
result += 1
continue
if symbol == "X" and next == "L":
result += 40
skip = True
continue
if symbol == "X" and next == "C":
result += 90
skip = True
continue
if symbol == "X":
result += 10
continue
if symbol == "C" and next == "D":
result += 400
skip = True
continue
if symbol == "C" and next == "M":
result += 900
skip = True
continue
if symbol == "C":
result += 100
continue
if symbol == "V":
result += 5
continue
if symbol == "D":
result += 500
continue
if symbol == "M":
result += 1000
continue
if symbol == "L":
result += 50
continue
raise Exception(f"unexpected situation: {symbol}, {next}")
return result
1568 - 2023-05-23 12:36:30 +0300 MSK
Two Sum
Links
Code
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
indexes = {}
for i, number in enumerate(nums):
diff = target - number
if diff in indexes:
return [indexes[diff], i]
indexes[number] = i
1569 - 2023-05-23 12:30:44 +0300 MSK
Two Sum
Links
Code
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i, number in enumerate(nums):
for j, number_inner in enumerate(nums[i+1:]):
if number + number_inner == target:
return [i, i+j+1]
1570 - 2022-05-17 07:59:02 +0300 MSK
Find a Corresponding Node of a Binary Tree in a Clone of That Tree
Links
Code
class Solution {
TreeNode ans;
public void inorder(TreeNode c,TreeNode target) {
if (c != null) {
inorder(c.left, target);
if (c.val == target.val) {
ans = c;
}
inorder(c.right, target);
}
}
public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target)
{
inorder(cloned,target);
return ans;
}
}
1571 - 2022-05-15 18:44:33 +0300 MSK
Deepest Leaves Sum
Links
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int deepestLeavesSum(TreeNode root) {
MaxDepthInfo maxDepthInfo = new MaxDepthInfo(0 ,0);
sumAtLevel(root, 0, maxDepthInfo);
return maxDepthInfo.getSumAtMaxDepth();
}
public void sumAtLevel(TreeNode root, int currentDepth, MaxDepthInfo maxDepthInfo) {
if (root == null) return;
if (currentDepth > maxDepthInfo.getMaxDepth()) {
maxDepthInfo.setMaxDepth(currentDepth);
maxDepthInfo.setSumAtMaxDepth(root.val);
}
else if (currentDepth == maxDepthInfo.getMaxDepth())
maxDepthInfo.setSumAtMaxDepth(maxDepthInfo.getSumAtMaxDepth() + root.val);
sumAtLevel(root.left, currentDepth + 1, maxDepthInfo);
sumAtLevel(root.right, currentDepth + 1, maxDepthInfo);
}
public static class MaxDepthInfo {
private int maxDepth;
private int sumAtMaxDepth;
public MaxDepthInfo(int maxDepth, int sumAtMaxDepth) {
this.maxDepth = maxDepth;
this.sumAtMaxDepth = sumAtMaxDepth;
}
public int getMaxDepth() { return maxDepth;}
public void setMaxDepth(int maxDepth) { this.maxDepth = maxDepth;}
public int getSumAtMaxDepth() { return sumAtMaxDepth;}
public void setSumAtMaxDepth(int sumAtMaxDepth) { this.sumAtMaxDepth = sumAtMaxDepth;}
}
}
1572 - 2022-05-14 15:28:36 +0300 MSK
Network Delay Time
Links
Code
class Solution {
private final Map<Integer, List<Node>> connected = new HashMap<>();
public int networkDelayTime(int[][] times, int n, int k) {
for (int[] time : times) {
connected.putIfAbsent(time[0], new ArrayList<>());
connected.get(time[0]).add(new Node(time[2], time[1]));
}
connected.forEach((source, nodes) -> nodes.sort(Comparator.comparing(Node::travelTime)));
int[] receivedTime = new int[n + 1]; Arrays.fill(receivedTime, 1, receivedTime.length, Integer.MAX_VALUE);
dfs(receivedTime, 0, k);
int max = Arrays.stream(receivedTime).max().orElseThrow(RuntimeException::new);
return max == Integer.MAX_VALUE ? -1 : max;
}
private void dfs(int[] receivedTime, int currentTime, int currentNode) {
if (receivedTime[currentNode] <= currentTime) return;
receivedTime[currentNode] = currentTime;
if (connected.containsKey(currentNode))
connected.get(currentNode).forEach(node -> dfs(receivedTime, currentTime + node.travelTime(), node.destination()));
}
public record Node(int travelTime, int destination) {}
}
1573 - 2022-05-13 07:19:10 +0300 MSK
Letter Combinations of a Phone Number
Links
Code
class Solution {
public List<String> letterCombinations(String digits) {
if(digits.length() == 0){
List<String> result = new ArrayList<>();
return result;
}
List<String> res = combine(digits);
return res;
}
public List<String> combine(String digit){
if(digit.length() == 0 ){
List<String> result = new ArrayList<>();
result.add("");
return result;
}
String[] codes = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
char c = digit.charAt(0);
String digits_left = digit.substring(1);
List<String> res = combine(digits_left);
List<String> result = new ArrayList<>();
String code_for_current_digit = codes[c-'0'];
for(int i=0;i<code_for_current_digit.length();i++){
char code_char = code_for_current_digit.charAt(i);
if(!res.isEmpty()){
for(String s : res){
result.add(code_char + s);
}
}
else{
res.add(String.valueOf(code_char));
}
}
return result;
}
}
1574 - 2022-05-13 07:17:45 +0300 MSK
Populating Next Right Pointers in Each Node II
Links
Code
class Solution {
public Node connect(Node root) {
Node leftMost = root;
while (leftMost != null) {
Node cur = leftMost;
leftMost = null;
Node pre = null;
while (cur != null) {
if (leftMost == null) {
leftMost = cur.left == null ? cur.right: cur.left;
}
if (pre != null) {
pre.next = cur.left == null ? cur.right : cur.left;
}
if (cur.left != null && cur.right != null) {
cur.left.next = cur.right;
}
pre = cur.right == null ? (cur.left == null ? pre : cur.left) : cur.right;
cur = cur.next;
}
}
return root;
}
}
1575 - 2022-05-12 18:05:33 +0300 MSK
Permutations II
Links
Code
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> permutations = new ArrayList<>();
Arrays.sort(nums);
backtracking(permutations, new ArrayList<>(), nums, new boolean[nums.length]);
return permutations;
}
private void backtracking(List<List<Integer>> permutations, List<Integer> current, int[] nums, boolean[] used) {
if (current.size() == nums.length)
permutations.add(new ArrayList<>(current));
else {
for (int i = 0; i < nums.length; i++) {
if (used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])) continue;
current.add(nums[i]);
used[i] = true;
backtracking(permutations, current, nums, used);
used[i] = false;
current.remove(current.size() - 1);
}
}
}
}
1576 - 2022-05-11 18:03:06 +0300 MSK
Count Sorted Vowel Strings
Links
Code
class Solution {
public int countVowelStrings(int n) {
int a,e,i,o,u;
a = e = i = o = u = 1;
for(int t = 1; t < n; t++){
a = a + e + i + o + u;
e = e + i + o + u;
i = i + o + u;
o = o + u;
u = u;
}
return a + e + i + o + u;
}
}
1577 - 2022-05-08 17:27:21 +0300 MSK
Flatten Nested List Iterator
Links
Code
public class NestedIterator implements Iterator<Integer> {
private List<Integer> integerList = new ArrayList<>();
private int index = 0;
public NestedIterator(List<NestedInteger> nestedList) {
for (NestedInteger nestedInteger : nestedList) {
flatten(nestedInteger);
}
}
private void flatten(NestedInteger nested) {
if (nested.isInteger())
integerList.add(nested.getInteger());
else
for (NestedInteger nestedFromList : nested.getList()) {
flatten(nestedFromList);
}
}
@Override
public boolean hasNext() {
return index < integerList.size();
}
@Override
public Integer next() {
return integerList.get(index++);
}
}
1578 - 2022-05-07 13:44:16 +0300 MSK
132 Pattern
Links
Code
func find132pattern(numbers []int) bool {
length := len(numbers)
if length < 3 {
// if the array doesn't have at least three numbers, it cannot have
// '123' pattern
return false
}
list, third_element := list.List{}, math.MinInt
for index := length - 1; index >= 0; index-- {
current := numbers[index]
if current < third_element {
return true
}
for list.Len() != 0 && list.Front().Value.(int) < current {
third_element = list.Front().Value.(int)
list.Remove(list.Front())
}
list.PushFront(current)
}
return false
}
1579 - 2022-05-07 13:05:13 +0300 MSK
Backspace String Compare
Links
Code
func backspaceCompare(string_1 string, string_2 string) bool {
length_1, length_2 := len(string_1), len(string_2)
list_1, list_2, length_biggest := list.List{}, list.List{}, length_1
if length_2 > length_1 {
length_biggest = length_2
}
for index := 0; index < length_biggest; index++ {
if index < length_1 {
backspace_action(&list_1, string_1[index])
}
if index < length_2 {
backspace_action(&list_2, string_2[index])
}
}
// lists are not equal, there is no need to check
if list_1.Len() != list_2.Len() {
return false
}
// checking elements after all deletions
element_1, element_2 := list_1.Back(), list_2.Back()
for element_1 != nil {
if element_1.Value != element_2.Value {
// elements are not equal -> strings are not equal
return false
}
element_1, element_2 = element_1.Next(), element_2.Next()
}
// checked all elements, strings are equal
return true
}
func backspace_action(list *list.List, character byte) {
switch {
case character == '#' && list.Len() != 0:
// delete last character
list.Remove(list.Front())
fallthrough
case character == '#' && list.Len() == 0:
// just return if the list is empty
return
}
list.PushFront(character)
}
1580 - 2022-05-06 20:02:58 +0300 MSK
Backspace String Compare
Links
Code
class Solution {
public boolean backspaceCompare(String S, String T) {
return build(S).equals(build(T));
}
public String build(String S) {
Stack<Character> ans = new Stack();
for (char c: S.toCharArray()) {
if (c != '#')
ans.push(c);
else if (!ans.empty())
ans.pop();
}
return String.valueOf(ans);
}
}
1581 - 2022-05-06 19:50:38 +0300 MSK
Remove Duplicates from Sorted Array
Links
Code
func removeDuplicates(numbers []int) int {
// ensure there are at least two numbers
length := len(numbers)
if length == 1 {
return 1
}
index_non_duplicate := 1
for index := 1; index < length; index++ {
current, previous := numbers[index], numbers[index-1]
if current == previous {
// it is a duplicate - ignore it
continue
}
// it is not a duplicate -> place it and move the index
numbers[index_non_duplicate] = current
index_non_duplicate++
}
return index_non_duplicate
}
1582 - 2022-05-06 19:25:00 +0300 MSK
Remove All Adjacent Duplicates in String II
Links
Code
class Solution {
public String removeDuplicates(String s, int k) {
Stack<int []> Master = new Stack<>();
for(char ch : s.toCharArray()){
if(!Master.isEmpty() && Master.peek()[0] == ch){
Master.peek()[1]++;
}
else Master.push(new int[]{ch, 1});
if(Master.peek()[1] == k) Master.pop();
}
StringBuilder sb = new StringBuilder();
while(!Master.isEmpty()){
int top[] = Master.pop();
while(top[1] --> 0)
sb.append((char)top[0]);
}
return sb.reverse().toString();
}
}
1583 - 2022-05-05 18:39:53 +0300 MSK
Sign of the Product of an Array
Links
Code
func arraySign(numbers []int) int {
negative_count := 0
for _, number := range numbers {
switch {
// the number is 0 -> product of all numbers is definitely zero
case number == 0:
return 0
// the number is negative -> add to count
case number < 0:
negative_count++
}
}
// even amount of negative numbers -> result is positive
if negative_count&1 == 0 {
return 1
}
// uneven amount of negative numbers -> result is negative
return -1
}
1584 - 2022-05-05 18:26:39 +0300 MSK
Find Smallest Letter Greater Than Target
Links
Code
func nextGreatestLetter(letters []byte, target byte) byte {
length := len(letters)
left, right := 0, length-1
for right >= left {
index := left + (right-left)/2
character := letters[index]
// the character is bigger, we found at least one result
// smaller characters are to the left -> discard right
if character > target {
right = index - 1
continue
}
// character is either equal or smaller -> there is no results to the
// left -> discard left
left = index + 1
}
return letters[left%length]
}
1585 - 2022-05-05 15:37:11 +0300 MSK
Sqrt(x)
Links
Code
func mySqrt(number int) int {
left, right := 0, number
for right >= left {
current := left + (right-left)/2
square_current := current * current
square_next := (current + 1) * (current + 1)
switch {
case square_current <= number && square_next > number:
// found the target
return current
case square_current > number:
// target is to the left -> discard right
right = current - 1
case square_current < number:
// target is to the right -> discard left
left = current + 1
}
}
return -1
}
1586 - 2022-05-05 15:10:54 +0300 MSK
Reverse Words in a String III
Links
Code
func reverseWords(_string string) string {
index_word_start, length, result := 0, len(_string), []rune(_string)
for index, character := range result {
// ignore normal characters
if character != ' ' {
continue
}
// word ended -> reverse characters from the start of the word to the
//end of it
reverse_word(result, length, index_word_start, index)
index_word_start = index + 1
}
reverse_word(result, length, index_word_start, length)
return string(result)
}
func reverse_word(_string []rune, length int, start int, end int) {
//fmt.Println("reversing", string(_string), start, "->", end)
length_word := end - start
for index := start; index < start+length_word/2; index++ {
index_last := end - (index - start) - 1
current, last := _string[index], _string[index_last]
_string[index], _string[index_last] = last, current
}
//fmt.Println("result", string(_string), start, "->", end)
}
1587 - 2022-05-05 13:50:33 +0300 MSK
Reverse String
Links
Code
func reverseString(characters []byte) {
length := len(characters)
for index := 0; index < length/2; index++ {
index_last := length - index -1
current, last := characters[index], characters[index_last]
characters[index_last] = current
characters[index] = last
}
}
1588 - 2022-05-05 13:43:47 +0300 MSK
Two Sum II - Input Array Is Sorted
Links
Code
func twoSum(numbers []int, target int) []int {
numbers_len := len(numbers)
for index, number := range numbers {
for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
if numbers[index_inner]+number == target {
return []int{index + 1, index_inner + 1}
}
}
}
return []int{}
}
1589 - 2022-05-05 13:39:30 +0300 MSK
Move Zeroes
Links
Code
func moveZeroes(numbers []int) {
index_zero := -1
// sliding window algorithm
for index, number := range numbers {
// if index_zero is not set, then the first zero is index_zero
if index_zero == -1 && number == 0 {
index_zero = index
}
// there is no need to move numbers if there were no zeros before
// there is no need to move zeros
if index_zero == -1 || number == 0 {
continue
}
// after some zeros we encounter a non-zero number
// moving that number to the beginning of zeros
numbers[index_zero] = number
// current number becomes zero
numbers[index] = 0
// moving the index
index_zero++
}
}
1590 - 2022-05-05 13:39:06 +0300 MSK
Move Zeroes
Links
Code
func moveZeroes(nums []int) {
count:=0
for i:=0; i<len(nums);i++{
if nums[i] == 0{
count++
}else{
nums[i-count]=nums[i]
}
}
for count>0{
nums[len(nums)-count] = 0
count--
}
}
1591 - 2022-05-05 13:38:25 +0300 MSK
Move Zeroes
Links
Code
func moveZeroes(nums []int) {
if len(nums) < 2 {
return
}
for z, p := 0, 1; p < len(nums) && z < len(nums); {
if nums[z] == 0 && nums[p] != 0 {
if p > z {
nums[z], nums[p] = nums[p], nums[z]
z++
}
p = z+1
} else {
if nums[z] != 0 {
z++
}
if nums[p] == 0 {
p++
}
}
}
}
1592 - 2022-05-05 13:32:58 +0300 MSK
Move Zeroes
Links
Code
func moveZeroes(numbers []int) {
index_zero := -1
// sliding window algorithm
for index, number := range numbers {
// if index_zero is not set, then the first zero is index_zero
if index_zero == -1 && number == 0 {
index_zero = index
}
// there is no need to move numbers if there were no zeros before
// there is no need to move zeros
if index_zero == -1 || number == 0 {
continue
}
// after some zeros we encounter a non-zero number
// moving that number to the beginning of zeros
numbers[index_zero] = number
// current number becomes zero
numbers[index] = 0
// moving the index
index_zero++
}
}
1593 - 2022-05-05 13:14:51 +0300 MSK
Move Zeroes
Links
Code
func moveZeroes(numbers []int) {
// ensure there are at least two numbers
length := len(numbers)
if length == 1 {
return
}
result, index_result := make([]int, length), 0
for _, number := range numbers {
if number == 0 {
continue
}
result[index_result] = number
index_result++
}
copy(numbers, result)
}
1594 - 2022-05-05 07:01:33 +0300 MSK
Implement Stack using Queues
Links
Code
type MyStack struct{ queue *list.List }
func Constructor() MyStack { return MyStack{&list.List{}} }
func (this *MyStack) Push(value int) { this.queue.PushFront(value) }
func (this *MyStack) Top() int { return this.queue.Front().Value.(int) }
func (this *MyStack) Empty() bool { return this.queue.Len() == 0 }
func (this *MyStack) Pop() int {
return this.queue.Remove(this.queue.Front()).(int)
}
1595 - 2022-05-04 13:13:54 +0300 MSK
Best Time to Buy and Sell Stock
Links
Code
func maxProfit(prices []int) int {
profit, index_buy := 0, 0
for index, price := range prices {
if prices[index_buy] > price {
index_buy = index
}
new_profit := price - prices[index_buy]
if new_profit > profit {
profit = new_profit
}
}
return profit
}
1596 - 2022-05-04 12:54:11 +0300 MSK
Intersection of Two Arrays II
Links
Code
func intersect(numbers_1 []int, numbers_2 []int) (result []int) {
// 0 <= nums1[i], nums2[i] <= 1000
count := make([]int, 1001)
// counting how many times a number occured in the first array
for _, number := range numbers_1 {
count[number]++
}
for _, number := range numbers_2 {
// the number did not occur in the first array
// -> ignoring it
if count[number] <= 0 {
continue
}
count[number]--
result = append(result, number)
}
return
}
1597 - 2022-05-04 12:36:38 +0300 MSK
Intersection of Two Arrays II
Links
Code
func intersect(numbers_1 []int, numbers_2 []int) []int {
length_1, length_2 := len(numbers_1), len(numbers_2)
length_biggest, result := length_1, make([]int, length_1+length_2)
if length_2 > length_1 {
length_biggest = length_2
}
occurences := make(map[int][]int, length_biggest)
for index := 0; index < length_biggest; index++ {
if index < length_1 {
add_to_occurences(numbers_1[index], 0, occurences)
}
if index < length_2 {
add_to_occurences(numbers_2[index], 1, occurences)
}
}
index := 0
for number, occurence := range occurences {
repeat := occurence[0]
if occurence[1] < repeat {
repeat = occurence[1]
}
for ; repeat > 0; repeat-- {
result[index] = number
index++
}
}
return result[0 : index]
}
func add_to_occurences(number int, index int, occurences map[int][]int) {
if _, occured := occurences[number]; !occured {
occurences[number] = make([]int, 2)
}
occurences[number][index]++
}
1598 - 2022-05-04 08:33:36 +0300 MSK
Merge Sorted Array
Links
Code
func merge(array1 []int, length1 int, array2 []int, length2 int) {
if length2 == 0 {
return
}
if length1 == 0 {
for index, number := range array2 {
array1[index] = number
}
return
}
index1, index2, array1Copy := 0, 0, make([]int, length1)
copy(array1Copy, array1)
for index := 0; index < length1+length2; index++ {
fmt.Println(index, index1, index2, array1, array2)
for index2 < length2 && (index1 >= length1 || array2[index2] <= array1Copy[index1]) {
array1[index] = array2[index2]
index2++
index++
}
if index1 >= length1 {
continue
}
array1[index] = array1Copy[index1]
index1++
}
}
1599 - 2022-05-04 08:32:16 +0300 MSK
Two Sum
Links
Code
func twoSum(numbers []int, target int) []int {
numbers_len := len(numbers)
for index, number := range numbers {
for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
if numbers[index_inner]+number == target {
return []int{index, index_inner}
}
}
}
return []int{}
}
1600 - 2022-05-04 08:30:20 +0300 MSK
Find the Distance Value Between Two Arrays
Links
Code
func findTheDistanceValue(array_1 []int, array_2 []int, target int) int {
// sorting it to use binary search
sort.Ints(array_2)
length_2, count := len(array_2), 0
for _, current_1 := range array_1 {
left, right, add_to_count := 0, length_2-1, true
for right >= left {
index := left + (right-left)/2
current_2 := array_2[index]
if abs(current_1, current_2) <= target {
// current_1 is inside |arr1[i]-arr2[j]| <= d
// -> ignore it
add_to_count = false
break
}
switch {
case current_2 > current_1:
// current_2 is bigger than current_1
// -> all numbers to the right are bigger
// -> discard right, add to count
right = index - 1
case current_2 < current_1:
// current_2 is smaller than current_1
// -> all numbers to the left are smaller
// -> discard left, add to count
left = index + 1
}
}
if add_to_count {
count++
}
}
return count
}
func abs(number_1 int, number_2 int) int {
difference := number_1 - number_2
if difference < 0 {
return difference * -1
}
return difference
}
1601 - 2022-05-04 07:34:24 +0300 MSK
Valid Perfect Square
Links
Code
func isPerfectSquare(number int) bool {
left, right := 1, number
for right >= left {
current := left + (right-left)/2
square := current * current
switch {
case square == number:
// found the target
return true
case square > number:
// square is bigger -> root is to the left -> discard right
right = current - 1
case square < number:
// square is smaller -> root is to the right -> discard left
left = current + 1
}
}
return false
}
1602 - 2022-05-04 07:03:31 +0300 MSK
Find Nearest Point That Has the Same X or Y Coordinate
Links
Code
func nearestValidPoint(x int, y int, points [][]int) int {
point_target, smallest_distance, smallest_index := []int{x, y}, math.MaxInt, -1
for index, point := range points {
// ignore the point if it is not valid
if !valid(point_target, point) {
continue
}
distance := distance(point_target, point)
// ignore the point if its Manhattan distance is bigger
if distance >= smallest_distance {
continue
}
// the distance is smaller, update the index and the distance
smallest_index, smallest_distance = index, distance
}
// there are no valid points
if smallest_index == -1 {
return -1
}
return smallest_index
}
func valid(point_target []int, point []int) bool {
switch {
case point_target[0] == point[0]:
fallthrough
case point_target[1] == point[1]:
return true
default:
return false
}
}
func distance(point_target []int, point []int) int {
return abs(point_target[0]-point[0]) + abs(point_target[1]-point[1])
}
func abs(number int) int {
if number < 0 {
return number * -1
}
return number
}
1603 - 2022-05-04 06:39:29 +0300 MSK
Largest Perimeter Triangle
Links
Code
func largestPerimeter(numbers []int) int {
sort.Ints(numbers)
for index := len(numbers) - 1; index > 1; index-- {
current, sum_previous := numbers[index], numbers[index-1]+numbers[index-2]
if current >= sum_previous {
continue
}
return current + sum_previous
}
return 0
}
1604 - 2022-05-04 06:26:24 +0300 MSK
Max Number of K-Sum Pairs
Links
Code
func maxOperations(numbers []int, sum int) int {
count, previous := 0, make(map[int]int, len(numbers))
for _, current := range numbers {
target := sum - current
target_unmatched, target_occured := previous[target]
// if the current number has not occured before, then it is not in the map
// -> it needs to be initialized
if _, current_occured := previous[current]; !current_occured {
previous[current] = 0
}
// number of duplicates of the current number has increased
previous[current]++
switch {
case target_occured && target_unmatched == 0:
// the target has occured before but there are no unmatched duplicates
fallthrough
case !target_occured:
// in order to get the sum we need the target, but it has not appeared yet
continue
case target_occured && target_unmatched > 0:
// the target has appeared before and there are some unmached duplicates left
// -> removing the current number and the target from possible matches
previous[current]--
previous[target]--
count++
}
}
return count
}
1605 - 2022-05-04 05:57:55 +0300 MSK
Subtract the Product and Sum of Digits of an Integer
Links
Code
func subtractProductAndSum(number int) int {
fist_digit := number % 10
factorial, sum := fist_digit, fist_digit
number /= 10
for number > 0 {
digit := number % 10
factorial *= digit
sum += digit
number /= 10
}
return factorial - sum
}
1606 - 2022-05-04 05:49:11 +0300 MSK
Number of 1 Bits
Links
Code
func hammingWeight(number uint32) (result int) {
for number > 0 {
if number&1 != 0 {
result++
}
number >>= 1
}
return
}
1607 - 2022-05-03 18:34:04 +0300 MSK
Peak Index in a Mountain Array
Links
Code
func peakIndexInMountainArray(array []int) int {
left, right := 0, len(array)-1
for right > left {
// overflow protection
index := left + (right-left)/2
// next element is bigger -> top is to the right -> discard left
if array[index+1] > array[index] {
left = index + 1
continue
}
// next element is equal or smaller -> discard right
// 'index' could be the answer, so it should not be discarded
right = index
}
return right
}
1608 - 2022-05-03 17:44:29 +0300 MSK
Search Insert Position
Links
Code
func searchInsert(numbers []int, target int) int {
// checking edge cases
length := len(numbers)
if numbers[0] == target {
return 0
} else if numbers[length-1] == target {
return length - 1
}
left, right, index, was_bigger := 0, length-1, 0, false
for right >= left {
// overflow protection
index = left + (right-left)/2
number := numbers[index]
//fmt.Println("index", index, "left", left, "right", right)
switch {
case number == target:
// found the target
return index
case number > target:
// the number is bigger -> the target is to the left -> discard right
right = index - 1
was_bigger = true
case number < target:
// the number is smaller -> the target is to the right -> discard left
left = index + 1
was_bigger = false
}
}
// the target is not in the array
// the last number was bigger -> target should be to the left
if was_bigger {
return index
}
// the last number was smaller -> target should be to the right
return index + 1
}
1609 - 2022-05-03 17:39:58 +0300 MSK
Rotate Array
Links
Code
func rotate(numbers []int, steps int) {
length := len(numbers)
// removing unnecessary steps
if steps >= length {
steps %= length
}
// checking edge cases
if length == 1 || steps == 0 {
return
}
results := make([]int, length)
for index, number := range numbers {
results[(index+steps)%length] = number
}
copy(numbers, results)
}
1610 - 2022-05-03 15:28:52 +0300 MSK
Rotate Array
Links
Code
func rotate(numbers []int, steps int) {
length := len(numbers)
// removing unnecessary steps
if steps >= length {
steps %= length
}
// checking edge cases
if length == 1 || steps == 0 {
return
}
remainder, rotation_start := make([]int, steps), length-steps
// copy everything that needs to be shifted to another array
copy(remainder, numbers[rotation_start:])
// move everything to the right
copy(numbers[steps:], numbers[0:rotation_start])
// move shifted elements to the beginning
copy(numbers[0:steps], remainder)
}
1611 - 2022-05-03 15:08:53 +0300 MSK
Squares of a Sorted Array
Links
Code
func sortedSquares(numbers []int) []int {
length := len(numbers)
if length == 0 || length == 1 {
return square(numbers, false)
}
negativesIndex := -1
for index, number := range numbers {
if number >= 0 {
negativesIndex = index
break
}
}
if negativesIndex == 0 || negativesIndex == -1 {
return square(numbers, negativesIndex == -1)
}
// fmt.Println("negativesIndex", negativesIndex)
result, resultIndex, negativesIndex := make([]int, length), 0, negativesIndex-1
for positivesIndex := negativesIndex + 1; resultIndex < length; positivesIndex++ {
positiveOverflow := positivesIndex >= length
for {
if negativesIndex < 0 || resultIndex >= length {
break
}
if !positiveOverflow && numbers[negativesIndex]*-1 > numbers[positivesIndex] {
break
}
result[resultIndex] = numbers[negativesIndex]
resultIndex++
// fmt.Println("negative", negativesIndex, resultIndex, numbers[negativesIndex], result, numbers)
negativesIndex--
}
if resultIndex < length && !positiveOverflow {
// fmt.Println("positivesIndex", positivesIndex, resultIndex, numbers[positivesIndex], result, numbers)
result[resultIndex] = numbers[positivesIndex]
resultIndex++
}
}
return square(result, false)
}
func square(array []int, reverse bool) []int {
if reverse {
length := len(array)
reversed := make([]int, length)
for index := length - 1; index >= 0; index-- {
reversed[length-index-1] = array[index] * array[index]
}
return reversed
} else {
for index, number := range array {
array[index] = number * number
}
return array
}
}
1612 - 2022-05-03 15:05:02 +0300 MSK
Squares of a Sorted Array
Links
Code
func sortedSquares(numbers []int) []int {
length := len(numbers)
switch length {
case 0:
return numbers
case 1:
return []int{numbers[0] * numbers[0]}
}
index_left, index_right := 0, length-1
results := make([]int, length)
for index := index_right; index_left <= index_right; index-- {
left_square := numbers[index_left] * numbers[index_left]
right_square := numbers[index_right] * numbers[index_right]
if right_square > left_square {
results[index] = right_square
index_right--
continue
}
results[index] = left_square
index_left++
}
return results
}
1613 - 2022-05-03 13:17:41 +0300 MSK
Shortest Unsorted Continuous Subarray
Links
Code
func findUnsortedSubarray(numbers []int) int {
length := len(numbers)
// checking edge cases
if length == 1 {
return 0
}
result := make([]int, length)
// initializing to MaxInt because zeros will impact future sorting
for index := range result {
result[index] = math.MaxInt
}
index_sort_start, index_sort_end := length, length
result[0] = numbers[0]
for index := 1; index < length; index++ {
// fmt.Println(result, index_sort_start, "->", index_sort_end)
// current is not sorted -> from numbers
// previous is sorted -> from result
current, previous := numbers[index], result[index-1]
// just push the current number in the result array because if it is
// bigger
if current >= previous {
result[index] = current
continue
}
// current number is not sorted -> moving the end index
index_sort_end = index + 1
// current < previous -> find the number bigger than the current
//
// the current number is smaller than the starting number of the unsorted subarray
// (or the starting index is not set)
// -> start index is invalid, finding new start index in numbers
if index_sort_start == length || current < result[index_sort_start] {
// insert the number in the correct place and move index_sort_start
// to the correct place
if index_sort_start == length {
// index_sort_start is not set -> setting to the last sorted number
index_sort_start = index - 1
}
index_sort_start = insert_smaller(result, current, index_sort_start, 0)
continue
}
// the current number is bigger than the starting number of the unsorted
// subarray, so it should be placed inside of it
insert_smaller(result, current, index, index_sort_start)
// set start index (if not already set)
if index < index_sort_start {
index_sort_start = index - 1
}
}
// fmt.Println(result, index_sort_start, "->", index_sort_end)
// return length of the sorted subarray
return index_sort_end - index_sort_start
}
func insert_smaller(numbers []int, target int, index_start int, index_end int) int {
index_result := index_end
for index := index_start; index >= index_end; index-- {
if target >= numbers[index] {
// target is bigger -> it should be placed after this index
index_result = index + 1
break
}
}
// fmt.Println("index for", target, "-", index_result)
// target should be placed after index_result, so move everything after
// it to the right and insert the current number
// if index_result is the last item, then just push it
copy(numbers[index_result+1:], numbers[index_result:])
numbers[index_result] = target
return index_result
}
1614 - 2022-05-03 13:17:21 +0300 MSK
Shortest Unsorted Continuous Subarray
Links
Code
func findUnsortedSubarray(numbers []int) int {
length := len(numbers)
// checking edge cases
if length == 1 {
return 0
}
result := make([]int, length)
// initializing to MaxInt because zeros will impact future sorting
for index := range result {
result[index] = math.MaxInt
}
index_sort_start, index_sort_end := length, length
result[0] = numbers[0]
for index := 1; index < length; index++ {
// fmt.Println(result, index_sort_start, "->", index_sort_end)
// current is not sorted -> from numbers
// previous is sorted -> from result
current, previous := numbers[index], result[index-1]
// just push the current number in the result array because if it is
// bigger
if current >= previous {
result[index] = current
continue
}
// current number is not sorted -> moving the end index
index_sort_end = index + 1
// current < previous -> find the number bigger than the current
//
// the current number is smaller than the starting number of the unsorted subarray
// (or the starting index is not set)
// -> start index is invalid, finding new start index in numbers
if index_sort_start == length || current < result[index_sort_start] {
// insert the number in the correct place and move index_sort_start
// to the correct place
if index_sort_start == length {
// index_sort_start is not set -> setting to the last sorted number
index_sort_start = index - 1
}
index_sort_start = insert_smaller(result, current, index_sort_start, 0)
continue
}
// the current number is bigger than the starting number of the unsorted
// subarray, so it should be placed inside of it
insert_smaller(result, current, index, index_sort_start)
// set start index (if not already set)
if index < index_sort_start {
index_sort_start = index - 1
}
}
// fmt.Println(result, index_sort_start, "->", index_sort_end)
// return length of the sorted subarray
return index_sort_end - index_sort_start
}
func insert_smaller(numbers []int, target int, index_start int, index_end int) int {
index_result := index_end
for index := index_start; index >= index_end; index-- {
if target >= numbers[index] {
// target is bigger -> it should be placed after this index
index_result = index + 1
break
}
}
// fmt.Println("index for", target, "-", index_result)
// target should be placed after index_result, so move everything after
// it to the right and insert the current number
// if index_result is the last item, then just push it
copy(numbers[index_result+1:], numbers[index_result:])
numbers[index_result] = target
return index_result
}
1615 - 2022-05-02 19:07:40 +0300 MSK
Sort Array By Parity
Links
Code
func sortArrayByParity(numbers []int) []int {
length := len(numbers)
if length == 1 {
return numbers
}
results, index_even, index_odd := make([]int, length), 0, length-1
for _, number := range numbers {
if (number & 1) == 0 {
// number is even -> place it from the beginning
results[index_even] = number
index_even++
} else {
// number is odd -> place it from the end
results[index_odd] = number
index_odd--
}
}
return results
}
1616 - 2022-05-02 18:49:07 +0300 MSK
Search Insert Position
Links
Code
func searchInsert(numbers []int, target int) int {
// checking edge cases
length := len(numbers)
if numbers[0] == target {
return 0
} else if numbers[length-1] == target {
return length - 1
}
left, right, index, was_bigger := 0, length-1, 0, false
for right >= left {
// overflow protection
index = left + (right-left)/2
number := numbers[index]
//fmt.Println("index", index, "left", left, "right", right)
switch {
case number == target:
// found the target
return index
case number > target:
// the number is bigger -> the target is to the left -> discard right
right = index - 1
was_bigger = true
case number < target:
// the number is smaller -> the target is to the right -> discard left
left = index + 1
was_bigger = false
}
}
// the target is not in the array
// the last number was bigger -> target should be to the left
if was_bigger {
return index
}
// the last number was smaller -> target should be to the right
return index + 1
}
1617 - 2022-05-02 18:02:36 +0300 MSK
First Bad Version
Links
Code
func firstBadVersion(n int) int {
// checking edge cases
if isBadVersion(1) {
return 1
}
left, right, bad_version := 1, n, math.MaxInt
for right >= left {
// overflow protection
version := left + (right-left)/2
switch isBadVersion(version) {
case false:
// it is good -> versions to the left are good -> discard left
left = version + 1
case true:
// it is bad -> the first bad version is either this one or to the left
// discard right
bad_version = version
right = version - 1
}
}
// the search space is empty
return bad_version
}
1618 - 2022-05-02 17:51:33 +0300 MSK
Binary Search
Links
Code
/* https://leetcode.com/problems/binary-search/
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
1 <= nums.length <= 104
-104 < nums[i], target < 104
All the integers in nums are unique.
nums is sorted in ascending order.
*/
package main
func search(numbers []int, target int) int {
length := len(numbers)
switch {
case numbers[0] > target:
// smallet number > target = there is no target in the array
fallthrough
case numbers[length-1] < target:
// biggest number < target = there is no target in the array
return -1
case numbers[length-1] == target:
// checking just in case, can save time
return length - 1
case numbers[0] == target:
// checking just in case, can save time
return 0
}
left, right := 0, length-1
for right >= left {
// overflow protection
index := left + (right-left)/2
number := numbers[index]
switch {
case number == target:
// found the target
return index
case number > target:
// array is in the ascending order, the number is bigger
// -> the target is to the left -> discard right
right = index - 1
case number < target:
// array is in the ascending order, the number is smaller
// -> the target is to the right -> discard left
left = index + 1
}
}
// search space is empty, there is no target
return -1
}
1619 - 2022-05-02 17:49:22 +0300 MSK
Guess Number Higher or Lower
Links
Code
func guessNumber(n int) int {
// checking edge cases
if guess(1) == 0 {
return 1
} else if guess(n) == 0 {
return n
}
left, right := 1, n
for right >= left {
// overflow protection
number := left + (right-left)/2
switch guess(number) {
case 0:
// found the target
return number
case -1:
// the number is bigger -> the target is to the left -> discard right
right = number - 1
case 1:
// the number is smaller -> the target is to the right -> discard left
left = number + 1
}
}
// ide shows an error, this return is unreachable in this issue
return 0
}
1620 - 2022-05-02 17:34:04 +0300 MSK
Binary Search
Links
Code
/* https://leetcode.com/problems/binary-search/
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
1 <= nums.length <= 104
-104 < nums[i], target < 104
All the integers in nums are unique.
nums is sorted in ascending order.
*/
package main
func search(numbers []int, target int) int {
length := len(numbers)
switch {
case numbers[0] > target:
// smallet number > target = there is no target in the array
fallthrough
case numbers[length-1] < target:
// biggest number < target = there is no target in the array
return -1
case numbers[length-1] == target:
// checking just in case, can save time
return length - 1
case numbers[0] == target:
// checking just in case, can save time
return 0
}
left, right := 0, length-1
for right >= left {
// overflow protection
index := left + (right-left)/2
number := numbers[index]
switch {
case number == target:
// found the target
return index
case number > target:
// array is in the ascending order, the number is bigger
// -> the target is to the left -> discard right
right = index - 1
case number < target:
// array is in the ascending order, the number is smaller
// -> the target is to the right -> discard left
left = index + 1
}
}
// search space is empty, there is no target
return -1
}
1621 - 2022-05-02 16:35:35 +0300 MSK
Average Salary Excluding the Minimum and Maximum Salary
Links
Code
func average(salary []int) float64 {
length := len(salary)
highest, lowest := math.MinInt, math.MaxInt
result := 0
for _, number := range salary {
result += number
if number > highest {
highest = number
}
if number < lowest {
lowest = number
}
}
return float64(result-highest-lowest) / float64(length-2)
}
1622 - 2022-05-02 16:28:49 +0300 MSK
Count Odd Numbers in an Interval Range
Links
Code
func countOdds(low int, high int) int {
low_even, high_even, half := (low&1) == 0, (high&1) == 0, (high-low)/2
if low_even && high_even {
return half
}
return half + 1
}
1623 - 2022-05-02 14:58:45 +0300 MSK
Maximum Subarray
Links
Code
func maxSubArray(numbers []int) int {
length := len(numbers)
switch length {
case 0:
return 0
case 1:
return numbers[0]
}
maxCurrent, maxOverall := 0, math.MinInt
for _, number := range numbers {
maxCurrent += number
if maxCurrent > maxOverall {
maxOverall = maxCurrent
}
if maxCurrent < 0 {
maxCurrent = 0
}
}
return maxOverall
}
1624 - 2022-05-02 07:24:29 +0300 MSK
Contains Duplicate
Links
Code
func containsDuplicate(numbers []int) bool {
if len(numbers) == 0 || len(numbers) == 1 {
return false
}
occured := make(map[int]bool)
for _, number := range numbers {
_, isDuplicate := occured[number]
if isDuplicate {
return true
}
occured[number] = true
}
return false
}
1625 - 2022-05-01 16:23:58 +0300 MSK
Add to Array-Form of Integer
Links
Code
func addToArrayForm(number1 []int, add int) []int {
if add == 0 {
return number1
}
if len(number1) == 0 {
return convert(add)
}
number2 := convert(add)
length1, length2, carry := len(number1), len(number2), 0
hightest := length1
if length2 > length1 {
hightest = length2
}
result := make([]int, hightest)
index1, index2, indexResult := length1-1, 0, hightest-1
for {
index1Valid, index2Valid := index1 >= 0, index2 < length2
if !index1Valid && !index2Valid && carry==0 {
break
}
digit1, digit2 := 0, 0
if index1Valid {
digit1 = number1[index1]
index1--
}
if index2Valid {
digit2 = number2[index2]
index2++
}
digitResult := digit1 + digit2 + carry
if digitResult > 9 {
carry = 1
digitResult -= 10
} else {
carry = 0
}
if indexResult == -1 {
result = append(result, 0)
copy(result[1:], result[0:hightest])
indexResult=0
}
result[indexResult] = digitResult
indexResult--
}
return result
}
func convert(number int) (result []int) {
for {
if number == 0 {
return
}
result = append(result, number%10)
number /= 10
}
}
1626 - 2022-05-01 15:41:08 +0300 MSK
Squares of a Sorted Array
Links
Code
func sortedSquares(numbers []int) []int {
length := len(numbers)
if length == 0 || length == 1 {
return square(numbers, false)
}
negativesIndex := -1
for index, number := range numbers {
if number >= 0 {
negativesIndex = index
break
}
}
if negativesIndex == 0 || negativesIndex == -1 {
return square(numbers, negativesIndex == -1)
}
//fmt.Println("negativesIndex", negativesIndex)
result, resultIndex, negativesIndex := make([]int, length), 0, negativesIndex-1
for positivesIndex := negativesIndex + 1; resultIndex < length; positivesIndex++ {
positiveOverflow := positivesIndex >= length
for {
if negativesIndex < 0 || resultIndex >= length {
break
}
if !positiveOverflow && numbers[negativesIndex]*-1 > numbers[positivesIndex] {
break
}
result[resultIndex] = numbers[negativesIndex]
resultIndex++
//fmt.Println("negative", negativesIndex, resultIndex, numbers[negativesIndex], result, numbers)
negativesIndex--
}
if resultIndex < length && !positiveOverflow {
// fmt.Println("positivesIndex", positivesIndex, resultIndex, numbers[positivesIndex], result, numbers)
result[resultIndex] = numbers[positivesIndex]
resultIndex++
}
}
return square(result, false)
}
func square(array []int, reverse bool) []int {
if reverse {
length := len(array)
reversed := make([]int, length)
for index := length - 1; index >= 0; index-- {
reversed[length-index-1] = array[index] * array[index]
}
return reversed
} else {
for index, number := range array {
array[index] = number * number
}
return array
}
}
1627 - 2022-05-01 13:28:32 +0300 MSK
Merge Sorted Array
Links
Code
func merge(array1 []int, length1 int, array2 []int, length2 int) {
if length2 == 0 {
return
}
if length1 == 0 {
for index, number := range array2 {
array1[index] = number
}
return
}
index1, index2, array1Copy := 0, 0, make([]int, length1)
copy(array1Copy, array1)
for index := 0; index < length1+length2; index++ {
//fmt.Println(index, index1, index2, array1, array2)
for index2 < length2 && (index1 >= length1 || array2[index2] <= array1Copy[index1]) {
array1[index] = array2[index2]
index2++
index++
}
if index1 >= length1 {
continue
}
array1[index] = array1Copy[index1]
index1++
}
}
1628 - 2022-05-01 13:12:45 +0300 MSK
Merge Sorted Array
Links
Code
func merge(array1 []int, length1 int, array2 []int, length2 int) {
index1, index2, array1Copy := 0, 0, make([]int, length1)
copy(array1Copy, array1)
for index := 0; index < length1+length2; index++ {
fmt.Println(index, index1, index2, array1, array2)
if index2 < length2 && (index1 >= length1 || array2[index2] <= array1Copy[index1]) {
array1[index] = array2[index2]
index2++
continue
}
array1[index] = array1Copy[index1]
index1++
}
}
1629 - 2022-05-01 09:06:49 +0300 MSK
Merge Two Sorted Lists
Links
Code
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
// ensure both lists are valid
switch {
case list1 == nil && list2 == nil:
return nil
case list1 == nil && list2 != nil:
return list2
case list1 != nil && list2 == nil:
return list1
}
var root *ListNode
if list1.Val < list2.Val {
root = &ListNode{list1.Val, nil}
list1 = list1.Next
} else {
root = &ListNode{list2.Val, nil}
list2 = list2.Next
}
current := &root
for {
switch {
case list1 == nil && list2 == nil:
return root
case list1 != nil && list2 != nil && list1.Val <= list2.Val:
fallthrough
case list1 != nil && list2 == nil:
fmt.Println("1", list1.Val)
updateResult(¤t, &list1)
case list1 != nil && list2 != nil && list1.Val > list2.Val:
fallthrough
case list1 == nil && list2 != nil:
fmt.Println("2", list2.Val)
updateResult(¤t, &list2)
}
}
}
func updateResult(current ***ListNode, node **ListNode) {
// modify the current result node
(**current).Next = &ListNode{(*node).Val, nil}
// move the current pointer
*current = &(**current).Next
// there is no next node -> nill it
// there is next -> move it
if (*node).Next == nil {
*node = nil
} else {
*node = (*node).Next
}
}
1630 - 2022-04-30 22:06:12 +0300 MSK
Valid Parentheses
Links
Code
func isValid(inputString string) bool {
if len(inputString) == 0 || (len(inputString)&1) != 0 {
return false
}
occurences := []rune{}
ends := map[rune]rune{')': '(', '}': '{', ']': '['}
for _, character := range inputString {
length := len(occurences)
last_valid, is_end := ends[character]
if (is_end && length == 0) || (is_end && occurences[length-1] != last_valid) {
return false
}
if is_end {
occurences = occurences[0 : length-1]
} else {
occurences = append(occurences, character)
}
}
if len(occurences) > 0 {
return false
}
return true
}
1631 - 2022-04-30 20:27:04 +0300 MSK
Find Palindrome With Fixed Length
Links
Code
func kthPalindrome(queries []int, intLength int) (answer []int64) {
for _, query := range queries {
answer = append(answer, getPalindrom(query, intLength))
}
return
}
func getPalindrom(query int, length int) (result int64) {
is_even := (length & 1) == 0
power := length / 2
if is_even {
power -= 1
}
palindrome := int64(math.Pow10(power)) + int64(query) - 1
result = palindrome
if !is_even {
palindrome /= 10
}
for palindrome > 0 {
result = result*10 + palindrome%10
palindrome /= 10
}
if len(fmt.Sprint(result)) != length {
return -1
}
return
}
1632 - 2022-04-30 18:34:48 +0300 MSK
Find Palindrome With Fixed Length
Links
Code
class Solution {
public long[] kthPalindrome(int[] queries, int intLength) {
long[] res= new long[queries.length];
for(int i=0;i<queries.length;i++){
res[i]=nthPalindrome(queries[i],intLength);
}
return res;
}
public long nthPalindrome(int nth, int kdigit)
{
long temp = (kdigit & 1)!=0 ? (kdigit / 2) : (kdigit/2 - 1);
long palindrome = (long)Math.pow(10, temp);
palindrome += nth - 1;
long res1=palindrome;
if ((kdigit & 1)>0)
palindrome /= 10;
while (palindrome>0)
{
res1=res1*10+(palindrome % 10);
palindrome /= 10;
}
String g="";
g+=res1;
if(g.length()!=kdigit)
return -1;
return res1;
}
}
1633 - 2022-04-30 09:12:31 +0300 MSK
Palindrome Number
Links
Code
func isPalindrome(number int) (result bool) {
if number < 0 {
return false
} else if number/10 == 0 {
return true
}
current := number
digits := []int{}
for {
if current == 0 {
break
}
digit := current % 10
current /= 10
digits = append(digits, digit)
}
digits_length := len(digits)
skip := -1
if digits_length%2 != 0 {
skip = digits_length / 2
}
for index, digit := range digits {
if index != skip && digit != digits[digits_length-index-1] {
return false
}
}
return true
}
1634 - 2022-04-30 08:49:48 +0300 MSK
Two Sum IV - Input is a BST
Links
Code
import "sort"
func construct(root *TreeNode, results map[int]int) {
if root == nil {
return
}
if results[root.Val] < 2 {
results[root.Val] += 1
}
construct(root.Left, results)
construct(root.Right, results)
}
func sorted(input_map map[int]int) (results []int) {
for key := range input_map {
results = append(results, key)
}
return
}
func findTarget(root *TreeNode, target int) bool {
if root == nil {
return false
}
results := map[int]int{}
construct(root, results)
if target%2 == 0 && results[target/2] == 2 {
return true
}
results_sorted := sorted(results)
results_sorted_len := len(results_sorted)
sort.Ints(results_sorted)
for index, number := range results_sorted {
for index_inner := index + 1; index_inner < results_sorted_len; index_inner++ {
if number+results_sorted[index_inner] == target {
return true
}
}
}
return false
}
1635 - 2022-04-30 08:49:00 +0300 MSK
Two Sum IV - Input is a BST
Links
Code
import "sort"
func construct(root *TreeNode, results map[int]bool, doubles map[int]bool) {
if root == nil {
return
}
_, exists := results[root.Val]
if !exists {
results[root.Val] = true
} else if _, double := doubles[root.Val]; exists && double {
doubles[root.Val] = true
}
construct(root.Left, results, doubles)
construct(root.Right, results, doubles)
}
func sorted(input_map map[int]bool) (results []int) {
for key := range input_map {
results = append(results, key)
}
return
}
func findTarget(root *TreeNode, target int) bool {
if root == nil {
return false
}
results := map[int]bool{}
doubles := map[int]bool{}
construct(root, results, doubles)
if _, double_exists := doubles[target/2]; target%2 == 0 && double_exists {
return true
}
results_sorted := sorted(results)
results_sorted_len := len(results_sorted)
sort.Ints(results_sorted)
for index, number := range results_sorted {
for index_inner := index + 1; index_inner < results_sorted_len; index_inner++ {
if number+results_sorted[index_inner] == target {
return true
}
}
}
return false
}
1636 - 2022-04-30 08:30:40 +0300 MSK
Two Sum IV - Input is a BST
Links
Code
import "sort"
func construct(root *TreeNode, results map[int]int) {
if root == nil {
return
}
if results[root.Val] < 2 {
results[root.Val] += 1
}
construct(root.Left, results)
construct(root.Right, results)
}
func sorted(input_map map[int]int) (results []int) {
for key := range input_map {
results = append(results, key)
}
return
}
func findTarget(root *TreeNode, target int) bool {
if root == nil {
return false
}
results := map[int]int{}
construct(root, results)
if target%2 == 0 && results[target/2] == 2 {
return true
}
results_sorted := sorted(results)
results_sorted_len := len(results_sorted)
sort.Ints(results_sorted)
for index, number := range results_sorted {
for index_inner := index + 1; index_inner < results_sorted_len; index_inner++ {
if number+results_sorted[index_inner] == target {
return true
}
}
}
return false
}
1637 - 2022-04-30 07:52:06 +0300 MSK
Two Sum IV - Input is a BST
Links
Code
func construct(root *TreeNode, results map[int]int) {
if root == nil {
return
}
if results[root.Val] < 2 {
results[root.Val] += 1
}
construct(root.Left, results)
construct(root.Right, results)
}
func findTarget(root *TreeNode, target int) bool {
results := map[int]int{}
construct(root, results)
for number, count := range results {
if count == 2 && number*2 == target {
return true
}
for number_inner := range results {
if number_inner <= number {
continue
}
if number+number_inner == target {
return true
}
}
}
return false
}
1638 - 2022-04-30 06:41:23 +0300 MSK
Two Sum II - Input Array Is Sorted
Links
Code
func twoSum(numbers []int, target int) []int {
numbers_len := len(numbers)
for index, number := range numbers {
for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
if numbers[index_inner]+number == target {
return []int{index + 1, index_inner + 1}
}
}
}
return []int{}
}
1639 - 2022-04-30 06:29:16 +0300 MSK
Two Sum
Links
Code
func twoSum(numbers []int, target int) []int {
numbers_len := len(numbers)
for index, number := range numbers {
for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
if numbers[index_inner]+number == target {
return []int{index, index_inner}
}
}
}
return []int{}
}
1640 - 2022-04-30 05:36:04 +0300 MSK
Add Two Numbers II
Links
Code
func reverse(list *ListNode) *ListNode {
if list == nil || list.Next == nil {
return list
}
result := &ListNode{list.Val, nil}
current := list.Next
for {
if current == nil {
return result
}
result = &ListNode{current.Val, result}
current = current.Next
}
}
func addTwoNumbers(list_1 *ListNode, list_2 *ListNode) *ListNode {
current_1, current_2, result := reverse(list_1), reverse(list_2), &ListNode{}
var carry int
result_current := result
for {
var value_1, value_2 int
if current_1 != nil {
value_1 = current_1.Val
current_1 = current_1.Next
}
if current_2 != nil {
value_2 = current_2.Val
current_2 = current_2.Next
}
sum := value_1 + value_2 + carry
if sum > 9 {
sum -= 10
carry = 1
} else {
carry = 0
}
result_current.Val = sum
if current_1 == nil && current_2 == nil && carry == 0 {
result_current.Next = nil
return reverse(result)
} else if current_1 == nil && current_2 == nil && carry != 0 {
current_1 = &ListNode{}
}
result_current.Next = &ListNode{}
result_current = result_current.Next
}
}
1641 - 2022-04-29 22:10:38 +0300 MSK
Add Two Numbers
Links
Code
func addTwoNumbers(list_1 *ListNode, list_2 *ListNode) *ListNode {
current_1, current_2, result := list_1, list_2, &ListNode{}
var carry int
result_current := result
for {
var value_1, value_2 int
if current_1 != nil {
value_1 = current_1.Val
current_1 = current_1.Next
}
if current_2 != nil {
value_2 = current_2.Val
current_2 = current_2.Next
}
sum := value_1 + value_2 + carry
if sum > 9 {
sum -= 10
carry = 1
} else {
carry = 0
}
result_current.Val = sum
if current_1 == nil && current_2 == nil && carry == 0 {
result_current.Next = nil
return result
} else if current_1 == nil && current_2 == nil && carry != 0 {
current_1 = &ListNode{}
}
result_current.Next = &ListNode{}
result_current = result_current.Next
}
}
1642 - 2022-04-29 19:52:46 +0300 MSK
Longest Common Prefix
Links
Code
func longestCommonPrefix(strings []string) string {
switch len(strings) {
case 0:
return ""
case 1:
return strings[0]
}
result := strings[0]
for index := 1; index < len(strings); index++ {
current := strings[index]
previous := strings[index-1]
current_max := len(current)
result_max := len(result)
var slice_max int
if result_max > current_max {
slice_max = current_max
result = result[0:slice_max]
} else {
slice_max = result_max
}
for ; slice_max >= 0; slice_max-- {
current_slice := current[0:slice_max]
if current_slice == previous[0:slice_max] {
result = current_slice
break
}
if slice_max == 0 {
return ""
}
}
}
return result
}
1643 - 2022-04-29 18:51:04 +0300 MSK
Longest Common Prefix
Links
Code
func substrings(input string) map[string]bool {
results := make(map[string]bool)
for index := range input {
results[input[0:index+1]] = true
}
return results
}
func string_in_maps(
source map[string]bool,
target map[string]bool,
results map[string]bool) {
for string := range source {
is_valid, exists_in_results := results[string]
_, exists_in_target := target[string]
switch {
case !exists_in_target:
fallthrough
case exists_in_target && (is_valid || !exists_in_results):
results[string] = exists_in_target
}
}
}
func longestCommonPrefix(strings []string) (result string) {
results := make(map[string]bool)
var previous map[string]bool
for index, string := range strings {
current := substrings(string)
if index == 0 {
previous = current
}
string_in_maps(previous, current, results)
string_in_maps(current, previous, results)
previous = current
}
for string, valid := range results {
if valid && len(string) > len(result) {
result = string
}
}
return
}
1644 - 2022-04-29 18:09:02 +0300 MSK
Longest Common Prefix
Links
Code
import "fmt"
func substrings(input string) map[string]bool {
results := make(map[string]bool)
for index := range input {
results[string(input[0:index+1])] = true
}
return results
}
func string_in_maps(
source map[string]bool,
target map[string]bool,
results map[string]bool) {
for string := range source {
if result, exists_in_results := results[string]; exists_in_results && !result {
continue
}
_, exists_in_target := target[string]
results[string] = exists_in_target
}
}
func longestCommonPrefix(strings []string) (result string) {
results := make(map[string]bool)
previous := make(map[string]bool)
for index, string := range strings {
current := substrings(string)
if index == 0 {
previous = current
}
string_in_maps(current, previous, results)
string_in_maps(previous, current, results)
fmt.Println("current string", string, current, "results", results)
previous = current
}
for string, valid := range results {
if !valid || len(string) < len(result) {
continue
}
if len(string) == len(result) && string < result {
result = string
continue
}
result = string
}
fmt.Println("result", result)
return
}
1645 - 2022-04-28 09:04:20 +0300 MSK
Roman to Integer
Links
Code
func romanToInt(input string) int {
var result int
types := map[rune]int{
'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
}
var previous rune
for _, character := range input {
result += types[character]
switch {
case previous == 'I' && (character == 'V' || character == 'X'):
fallthrough
case previous == 'X' && (character == 'L' || character == 'C'):
fallthrough
case previous == 'C' && (character == 'D' || character == 'M'):
result -= types[previous] * 2
}
previous = character
}
return result
}
1646 - 2022-04-28 08:59:35 +0300 MSK
Roman to Integer
Links
Code
func in(character rune, targets string) bool {
for _, target := range targets {
if character == target {
return true
}
}
return false
}
func romanToInt(roman string) int {
type dict map[rune]int
var result int
input := []rune(roman)
types := dict{
'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
}
var previous rune
for _, character := range input {
result += types[character]
switch {
case previous == 'I' && in(character, "VX"):
fallthrough
case previous == 'X' && in(character, "LC"):
fallthrough
case previous == 'C' && in(character, "DM"):
result -= types[previous] * 2
}
previous = character
}
return result
}
1647 - 2022-04-28 08:59:06 +0300 MSK
Roman to Integer
Links
Code
func in(character rune, targets string) bool {
for _, target := range targets {
if character == target {
return true
}
}
return false
}
func romanToInt(roman string) int {
type dict map[rune]int
var result int
types := dict{
'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
}
for index, character := range roman {
result += types[character]
if index < 1 {
continue}
switch {
case roman[index-1] == 'I' && in(character, "VX"):
fallthrough
case roman[index-1] == 'X' && in(character, "LC"):
fallthrough
case roman[index-1] == 'C' && in(character, "DM"):
result -= types[rune(roman[index-1])] * 2
}
}
return result
}
1648 - 2022-04-28 08:55:16 +0300 MSK
Roman to Integer
Links
Code
func in(character rune, targets string) bool {
for _, target := range targets {
if character == target {
return true
}
}
return false
}
func romanToInt(roman string) int {
type dict map[rune]int
var result int
input := []rune(roman)
types := dict{
'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
}
var previous rune
for _, character := range input {
result += types[character]
switch {
case previous == 'I' && in(character, "VX"):
fallthrough
case previous == 'X' && in(character, "LC"):
fallthrough
case previous == 'C' && in(character, "DM"):
result -= types[previous] * 2
}
previous = character
}
return result
}